package com.wawayaya.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.wawayaya.AppContext;
import com.wawayaya.api.remote.ApiConstans;
import com.wawayaya.bean.ReadRecord;
import com.wawayaya.bookreader.DefaultSettings;
import com.wawayaya.bookreader.Imutualaction;
import com.wawayaya.bookreader.SettingBtnClicked;
import com.wawayaya.bookreader.TouchMoveButton;
import com.wawayaya.bookreader.TouchMoveLinearLayout;
import com.wawayaya.bookreader.ViewPages.CustomViewPager;
import com.wawayaya.bookreader.ViewPages.NewBookPageView;
import com.wawayaya.bookreader.ViewPages.NewQuizView;
import com.wawayaya.bookreader.ViewPages.NewViewPagerAdapter;
import com.wawayaya.bookreader.bean.Bookpagesummary;
import com.wawayaya.bookreader.bean.EnDictData;
import com.wawayaya.bookreader.bean.KokRegion;
import com.wawayaya.bookreader.bean.Pagedata;
import com.wawayaya.bookreader.bean.Pagesdata;
import com.wawayaya.bookreader.bean.StringDouble;
import com.wawayaya.bookreader.jni.Audio2Wav;
import com.wawayaya.bookreader.jni.Brush;
import com.wawayaya.bookreader.jni.PinyinConvert;
import com.wawayaya.bookreader.speedregulation.SpeedConvertItem;
import com.wawayaya.bookreader.speedregulation.SpeedRegulationThread;
import com.wawayaya.bookreader.thumbnail.BottomGallery;
import com.wawayaya.bookreader.thumbnail.BottomGalleryAdapter;
import com.wawayaya.bookreader.thumbnail.BottomGalleryDataObj;
import com.wawayaya.bookreader.worddict.NewViewWordDictdesc;
import com.wawayaya.bookreader.worddict.WordDictdescData;
import com.wawayaya.cache.UserDataCache;
import com.wawayaya.util.Devicescreenbasicinfo;
import com.wawayaya.util.FileUtil;
import com.wawayaya.util.PreferenceUtils;
import com.wawayaya.util.TLog;
import com.wbtech.ums.UmsAgent;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import wawayaya.kids_iread.R;

/**
 * ReadBookActivity
 * 图书阅读  activity
 * @author  wq
 * @version 1.0
 * @created 2015-11-3
 */
public class ReadBookActivity extends Activity implements Imutualaction, SettingBtnClicked {

    private final static String TAG = "NewReadBookActivity";


    private final static int ms_iautokokon = 0;
    private final static int ms_iautokokoff = 1;
    private final static int ms_iautokokwait = 2;
    private final static int MSG_HIDEDICTVIEW = 1;
    private final static int MSG_DELAYSTARTAUTOKOK = 4;
    private final static int MSG_PAGEOPENSTARTAUTOKOK = 5;

    private Intent m_it = null;
    private int m_icatalogid = -1;
    private int m_iitemid = -1;

    private long m_lactivitystarttime = 0;
    private RelativeLayout m_rlreadbook = null;
    private RelativeLayout m_rlrealreadbook = null;
    private ImageView m_ivhorizonwait = null;

    private ViewPager m_vpbookpage = null;
    private NewViewPagerAdapter m_vpapagesadapter = null;
    private int m_ibooknetid = 0;
    private int m_ibookid = 0;
    private int m_inowpagepos = -1;
    private int m_ikokcolor = Color.RED;
    private Pagesdata m_psds[] = null;
    private String[] m_sspartssers = null;
    private Pagesdata m_pdcurrent = null;
    private float m_fratiox = 1.0f;
    private float m_fratioy = 1.0f;

    private boolean m_bisbooklandscape = false;
    private Devicescreenbasicinfo m_dsi = null;

    private RelativeLayout m_rlbooktopfloatbar = null;
    private Button m_bntobookshelf = null;
    private TextView m_tvbookname = null;
    private LinearLayout m_llpagenumber = null;
    private TextView m_pagename = null;
    private TextView m_tvcurpage = null;
    private TextView m_tvpagecut = null;
    private TextView m_tvtotalpage = null;

    private LinearLayout m_llsettingsregion = null;
    private LinearLayout m_llsettingsitems = null;
    private TouchMoveButton m_bnbooksettings = null;
    private Button m_bnautokok = null;
    private boolean m_bautokok = true;
    private Button m_bnshowpinyin = null;
    private int m_ishowpinyin = 0; // 0, hide; 1, show 
    private Button m_bnshowAnotherLan = null;
    private int m_ishowAnotherLan = 0; // 0, hide; 2, show
    private Button m_bnshowtrans = null;
    private int m_ishowthrans = 0;

    private static Drawable[] m_dwautokokon = null;
    private static Drawable m_dwautokokoff = null;
    private static Drawable m_dwautokokwait = null;
    private Timer m_tmkok = null;
    private TimerTask m_ttkoktask = null;
    private boolean m_bonbakcpressed = false;
    private boolean m_bonWindowFocusChanged = false;
    private boolean m_boncreated = false;

    private AtomicInteger m_bworddictisshow = new AtomicInteger(0);
    private NewViewWordDictdesc m_vwdworddictcontainer = null;
    private WordDictdescData m_wddworddictdata = null;
    private int   mWordDictShowFromX = 0;
    private int   mWordDictShowFromY = 0;
    private ScaleAnimation mWordDictShowAnim;
    private ScaleAnimation mWordDictHideAnim;

    private long m_llastscrolltime = 0;

    private static LinkedList<Integer> m_lliids = null;
    private static int m_iidscount = 0;

    private RequestQueue m_rqvolley = null;

    private int m_ibd_totalcount = 0;
    private int m_ibd_bookpages = 0;
    private String m_sbd_bookname = "";
    private boolean m_bbd_haskok = false;
    private boolean m_bbd_haspinyin = false;
    private boolean m_bbd_hasenglish = false;
    //private boolean m_bbd_hastranslation = false;
    private int m_ibd_showbookspage = 0;
    private boolean m_bbd_hasquiz = false;
    private String m_sbd_dictimgprefixurl = null;
    private String m_sbd_dictsoundprefixurl = null;
    private String m_sbd_quizprefixurl = null;
    private String m_quizurl = null;
    private boolean m_bhasbeeninited = false;
    private int m_ireadtype = DefaultSettings.BOOKREADTYPE_READTOME;
    private boolean m_bresotedfrompause = false;

    private final static int WAITANIMFRAME_ACCOUNT = 8;
    private int m_waitanimres[] = new int[WAITANIMFRAME_ACCOUNT];
    private BitmapDrawable m_bdwaitanim[] = new BitmapDrawable[WAITANIMFRAME_ACCOUNT];

    private ViewPagerTransformer m_readtometransfwer = null;
    private String m_sappver = "1.0.41";
    private WakeLock m_WakeLock = null;

    // 0, settings collapsed; 2, settings expanded
    private AtomicInteger m_isettingsshow = new AtomicInteger(2);
    // 0, float-bar invisible; 2, float-bar visible
    private AtomicInteger m_ifloatbarshow = new AtomicInteger(2);

    private RelativeLayout mBottomGalleryLayout;
    private BottomGallery mBottomGallery;
    private BottomGalleryAdapter mGalleryAdapter;
    private ArrayList<BottomGalleryDataObj> mGalleryDataList;
    // 0, float-bar invisible; 1, from invisible to visible; -1, from visible to invisible; 2, float-bar visible
    private AtomicInteger m_bottomGalleryShow = new AtomicInteger(2);


    private RelativeLayout mBookMarkLayout;
    private ImageButton mReadToMeBtn;
    private ImageButton mReadByMySelfBtn;
    private Animation mBookmarkOut;
    private Animation mBookmarkIn;
    // 0, float-bar invisible; 1, from invisible to visible; -1, from visible to invisible; 2, float-bar visible
    private AtomicInteger m_bookmarkShow = new AtomicInteger(0);
    private ImageView mHandView;
    private Animation mHandAnim;


    private TouchMoveLinearLayout mTransLayout;
    private TextView mTranView;
    // 0,  invisible; 1, invisible to visible; -1, from visible to invisible; 2, visible
    private AtomicInteger m_transShow = new AtomicInteger(0);
    private Animation mTransShowScaleAnimation;
    private Animation mTransHideScaleAnimation;


    private int mScreenWidth;
    private int mScreenHeight;
    private float mSceenDensity;


    public static final  int SPEED_NORMAL = 0;
    public static final  int SPEED_FAST = 1;
    public static final  int SPEED_SLOW = 2;
    private SpeedRegulationThread mSpeedConvertThread = null;
    private  boolean[]  mSpeedConvertState;
    private Button m_bnshowspeed = null;
    private boolean  mSpeedBtnShow = false;
    private int mCurrentSpeed = SPEED_NORMAL;
    private int mOldSpeed = SPEED_NORMAL;



  //  private ReadRecordEntityDao recordDao;
    private Context context;

    public static int getexclusivetagId() {
        initexclusivetagIds();
        if (!m_lliids.isEmpty()) {
            return m_lliids.removeFirst();
        }
        int ilastcount = m_iidscount;
        m_iidscount *= 2;
        for (int i = ilastcount + 1; i <= m_iidscount; i++) {
            m_lliids.add(i);
        }
        return m_lliids.removeFirst();
    }

    public static void freeexclusivetagId(int itagid) {
        initexclusivetagIds();
        m_lliids.addFirst(itagid);
    }

    private static void initexclusivetagIds() {
        if (null == m_lliids) {
            m_iidscount = 16;
            m_lliids = new LinkedList<Integer>();
            for (int i = 1; i <= m_iidscount; i++) {
                m_lliids.add(i);
            }
        }
    }

    private void umsOnCreate(long suserId) {
        UmsAgent.onError(this);
        UmsAgent.bindUserIdentifier(this, suserId+"");
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.reader_book);

        this.preInit();
    }
    long userId = 0L;
    private void  preInit(){
        context = this;
        userId  = UserDataCache.getInstance().getUid();
        Audio2Wav.initialize(null);   //调节语速
        Brush.initialize("");         //笔画
        PinyinConvert.initialize(""); //拼语

        m_it = getIntent();
        Bundle bd = m_it.getExtras();

        try {
            PackageInfo info;
            info = getPackageManager().getPackageInfo(getPackageName(), 0);
            m_sappver = info.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        umsOnCreate(userId);
        m_icatalogid = bd.getInt(DefaultSettings.BUNDLE_CATALOGID);
        m_iitemid = bd.getInt(DefaultSettings.BUNDLE_ITEMID);

        m_sspartssers = bd.getStringArray(DefaultSettings.BUNDLE_SERIALIZEDPARTPATH);
        if (null == m_sspartssers || m_sspartssers.length <= 0) {
            return;
        }

        m_ibooknetid = bd.getInt(DefaultSettings.BUNDLE_BOOKNETID);
        m_ibookid = bd.getInt(DefaultSettings.BUNDLE_BOOKID);

        m_sbd_bookname = bd.getString(DefaultSettings.BUNDLE_BOOKNAME);
        m_sbd_dictimgprefixurl = PreferenceUtils.getConfigUrlByKey(ApiConstans.CONFIG_PEITU, context);
        m_sbd_dictsoundprefixurl = PreferenceUtils.getConfigUrlByKey(ApiConstans.CONFIG_DUYIN, context);
        m_sbd_quizprefixurl =  PreferenceUtils.getConfigUrlByKey(ApiConstans.CONFIG_QUIZ,context);


        m_ireadtype = PreferenceUtils.getReadBookMode(context, m_ibookid, userId+"") ? DefaultSettings.BOOKREADTYPE_READTOME
                : DefaultSettings.BOOKREADTYPE_READMYSELF;
        if (DefaultSettings.BOOKREADTYPE_READTOME == m_ireadtype) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }

        m_psds = new Pagesdata[m_sspartssers.length];
        for (int i = 0; i < m_sspartssers.length; i++) {
            try {
                File file = new File(m_sspartssers[i]);
                if(file.exists()){
                    m_psds[i] = FileUtil.unserializebookpartpage(m_sspartssers[i]);
                }else{
                    m_psds[i] = null;
                }
            } catch (Exception e) {
                TLog.log("e error........." + e.toString());
                e.printStackTrace();
                m_psds[i] = null;
            }
        }

        if (null == m_psds) {
            return;
        }

        if (null == m_rqvolley) {
            try {
                m_rqvolley = Volley.newRequestQueue(this, FileUtil.getireadckclocaldictionaryfolder(FileUtil.getparentfolder(AppContext.bookzipsavedpath)));
            } catch (Exception e) {
                return;
            }
            m_rqvolley.start();
        }

        int isize = PreferenceUtils.readdeviceheapgrowthlimit(this);
        boolean bsmall = true;//(isize <= 96);
        m_waitanimres[0] = bsmall ? R.drawable.bookpagewait01s : R.drawable.bookpagewait01;
        m_waitanimres[1] = bsmall ? R.drawable.bookpagewait02s : R.drawable.bookpagewait02;
        m_waitanimres[2] = bsmall ? R.drawable.bookpagewait03s : R.drawable.bookpagewait03;
        m_waitanimres[3] = bsmall ? R.drawable.bookpagewait04s : R.drawable.bookpagewait04;
        m_waitanimres[4] = bsmall ? R.drawable.bookpagewait05s : R.drawable.bookpagewait05;
        m_waitanimres[5] = bsmall ? R.drawable.bookpagewait06s : R.drawable.bookpagewait06;
        m_waitanimres[6] = bsmall ? R.drawable.bookpagewait07s : R.drawable.bookpagewait07;
        m_waitanimres[7] = bsmall ? R.drawable.bookpagewait08s : R.drawable.bookpagewait08;
        for (int i = 0; i < WAITANIMFRAME_ACCOUNT; i++) {
            m_bdwaitanim[i] = null;
        }

        Pagesdata m_pdfirst = getcurrentpagesdataobj(0, false);
        if (m_pdfirst != null) {
            m_ibd_totalcount = m_pdfirst.getbooktotalpagescount();
            m_ibd_bookpages = m_pdfirst.getcontentpagecount();
        }
        if (m_ibd_totalcount < 1) {
            quitactivityforerrordata();
            return;
        }
        //转换当前页的语速
        mSpeedConvertState = new boolean[m_ibd_totalcount];
        for (int i = 0; i < m_ibd_totalcount; i++) {
            mSpeedConvertState[i]  = false;
        }


        if (DefaultSettings.BOOKREADTYPE_READTOME == m_ireadtype) {
            m_inowpagepos = 0;
            if (null != m_vpapagesadapter) {
                m_vpapagesadapter.recordselectedpage(m_inowpagepos);
                TLog.log("Activities  1 recordselectedpage " + m_inowpagepos);
            }
            //autodoreadtometypeotherpage();
        } else {
            int ilastinnerpage = getlastreadinnerpage();
            if (ilastinnerpage >= 0 && ilastinnerpage < m_ibd_totalcount) {
                m_inowpagepos = ilastinnerpage;
            } else {
                m_inowpagepos = 0;
            }
            if (null != m_vpapagesadapter) {
                TLog.log("Activities  2 recordselectedpage " + m_inowpagepos);
                m_vpapagesadapter.recordselectedpage(m_inowpagepos);
            }
        }


        if (0 == m_inowpagepos) {
            m_pdcurrent = m_pdfirst;
        } else {
            m_pdcurrent = getcurrentpagesdataobj(m_inowpagepos, false);
        }

        //setScreenOrientation(bd.getInt(ConstValues.BUNDLE_BOOKORIENTATION));
        setScreenOrientation(m_pdcurrent.isLandScapeBook() ? DefaultSettings.BOOK_ORIENTATION_LANDSCAPE : DefaultSettings.BOOK_ORIENTATION_PORTRAIT );
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mScreenWidth = dm.widthPixels;
        mScreenHeight = dm.heightPixels;
        mSceenDensity = dm.density;

        m_ireadtype = DefaultSettings.BOOKREADTYPE_READMYSELF;

        if (!m_pdcurrent.pageisin(m_inowpagepos)) {
            m_inowpagepos = m_pdcurrent.getbegininnerpageidx();
            if (null != m_vpapagesadapter) {
                TLog.log("Activities  3 recordselectedpage " + m_inowpagepos);
                m_vpapagesadapter.recordselectedpage(m_inowpagepos);
            }
        }

        if (!TextUtils.isEmpty(m_quizurl)) {
            m_bbd_hasquiz = true;
        }
        //m_bbd_hasquiz = m_pdcurrent.hasquiz();
        m_ibd_showbookspage = m_ibd_totalcount;
        m_ibd_bookpages = m_pdcurrent.getcontentpagecount();
        if (m_bbd_hasquiz) {
            m_ibd_showbookspage -= m_pdcurrent.getbackcoverpagecount();
        }
        // 2014-11-04 end.
        m_rlreadbook = (RelativeLayout) findViewById(R.id.fl_readbook);
        m_rlrealreadbook = (RelativeLayout) findViewById(R.id.fl_realreadbook);
        m_ikokcolor = m_pdcurrent.getKokColor();
/*        if (checkscreenbasicinfoexisted(m_pdcurrent)) {
            initView();
            m_bhasbeeninited = true;
        } else {
            MyLog.d("DSI gethere");
            showhorizontalbookwaitingpage(true);
        }*/

        if (!checkscreenbasicinfoexisted(m_pdcurrent)) {
            updatescreenbasicinfo(mScreenWidth, mScreenHeight, m_bisbooklandscape);
        }
        initView();
        m_bhasbeeninited = true;
        m_boncreated = true;
        this.loadData();
    }

    private void  loadData(){
        this.addRecord();
    }

    private void initView() {
        m_fratiox = m_dsi.m_iScreenWidth / m_dsi.m_fscreendensity / DefaultSettings.getstandardWidth(m_bisbooklandscape);
        m_fratioy = m_dsi.m_iScreenHeight / m_dsi.m_fscreendensity / DefaultSettings.getstandardHeight(m_bisbooklandscape);
        getautokokstatus();
        getpinyinstatus();
        getenglishstatus();

        setbooktopFloatBar(m_sbd_bookname, m_ibd_bookpages);

        initworddictdescview();
        initTransLayout();

        initBottomGallery();
        initBookMark();
        //setbookedgeSettingsBar(m_bbd_haskok, m_bbd_haspinyin, m_bbd_hasenglish/*, m_bbd_hastranslation*/);
        initbookedgeSettingsBar();


        m_vpbookpage = (ViewPager) findViewById(R.id.vp_bookpage);
        m_vpbookpage.setSaveEnabled(false);
        m_vpapagesadapter = new NewViewPagerAdapter(this,
                m_ibd_showbookspage, m_ibd_bookpages, /*m_bbd_hasquiz ? 1 : 0,*/ m_psds,
                this,
                m_ibooknetid, m_ibookid,
                m_ikokcolor,
                m_dsi,
                m_waitanimres,
                m_bdwaitanim,
                m_ireadtype, m_quizurl);
        if (m_inowpagepos >= 0) {
            TLog.log("Activities  4 recordselectedpage " + m_inowpagepos);
            m_vpapagesadapter.recordselectedpage(m_inowpagepos);
        }


        m_vpbookpage.setAdapter(m_vpapagesadapter);
        m_vpbookpage.setOnPageChangeListener(pagechangelistener);
        m_vpbookpage.setCurrentItem(m_inowpagepos);



        if (m_vpapagesadapter.isquizview(m_inowpagepos)) {
            m_bottomGalleryShow.set(0);
            mBottomGalleryLayout.setVisibility(View.GONE);
        }

        //m_vpbookpage.setOnTouchListener(viewpagerTouchListenr);

        try {
            if (DefaultSettings.ms_Json_BookPageType_page != m_pdcurrent.getpagedata(m_inowpagepos).getpageType()) {
                m_llpagenumber.setVisibility(View.INVISIBLE);
                m_llsettingsregion.setVisibility(View.INVISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        m_lactivitystarttime = System.currentTimeMillis();

        if (m_inowpagepos > 0) {
            if (m_bautokok && null != m_hscrollwaitautokok) {
                Message msg = new Message();
                msg.what = MSG_PAGEOPENSTARTAUTOKOK;
                msg.arg1 = m_inowpagepos;
                m_hscrollwaitautokok.sendMessageDelayed(msg, 600);
            } else if (!m_bautokok) {
                setautokokstatus(ms_iautokokoff);
            }
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        TLog.log("NewReadBookActivity.....onWindowFocusChanged");
/*
        if(m_boncreated && hasFocus) {
            ((wawayayareaderApplication)getApplication()).getBookReaderOnHandler().sendEmptyMessage(0);
        }        */
        if (!m_bhasbeeninited) {
            if (null != m_rlreadbook) {
                int iw = m_rlreadbook.getWidth();
                int ih = m_rlreadbook.getHeight();
                if (iw > 0 && ih > 0) {
                    updatescreenbasicinfo(iw, ih, m_bisbooklandscape);
                    m_pdcurrent.updatecharacterposition(iw, ih);
                    updateseerializedbookpartpage(m_pdcurrent);
                    initView();
                    showhorizontalbookwaitingpage(false);
                    m_bhasbeeninited = true;
                }
            }
        }
        if (m_boncreated && m_bisbooklandscape) {
            for (int i = 0; i < m_psds.length; i++) {
                if (null != m_psds[i]) {
                    checkandupdatelandscapebookpagesdata(m_psds[i]);
                } else {
                    break;
                }
            }
        }
        m_boncreated = false;
        m_bonWindowFocusChanged = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        UmsAgent.onResume(this);

        if (DefaultSettings.BOOKREADTYPE_READTOME == m_ireadtype && m_bresotedfrompause) {
            m_bautokok = true;
            try {
                NewBookPageView bpv = m_vpapagesadapter.getbookpageview(m_inowpagepos);
                if (null != bpv) {
                    bpv.setautokok(true, m_inowpagepos);
                }
            } catch (Exception e) {
            }
            PowerManager pManager = ((PowerManager) getSystemService(POWER_SERVICE));
            m_WakeLock = pManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG);
            m_WakeLock.acquire();
        }
        m_bresotedfrompause = false;
    }

    @Override
    public void onPause() {
        TLog.log("Activities NewReadBookActivity onPause");
        UmsAgent.onPause(this);

        m_boncreated = false;
        closekokplaying();
        if (m_bworddictisshow.get() > 0) {
            backpressclosedictionary(false);
        }
        if (m_bonWindowFocusChanged && !m_bonbakcpressed) {
            if (m_bautokok) {
                m_bautokok = false;
                setautokokstatus(ms_iautokokoff);
                m_bresotedfrompause = true;
            }
        }
        savequitstatus();
        super.onPause();
        try {
            if (null != m_WakeLock) {
                m_WakeLock.release();
                m_WakeLock = null;
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void onBackPressed() {
        m_boncreated = false;
        if (System.currentTimeMillis() - m_lactivitystarttime <= 1000) {
            return;
        }
        if (m_bworddictisshow.get()>0) {
            backpressclosedictionary(true);
            return;
        } if (m_transShow.get() > 0) {
            hideTransLayoutWithoutAnimation();
            return;
        } /*else if (null != m_vpapagesadapter && m_vpapagesadapter.quitquizview(m_inowpagepos)) {
            return;
        }*/
        closekokplaying();
        m_bonbakcpressed = true;
        if (null != m_vpapagesadapter) {
            m_vpapagesadapter.tostopwaitinganim();
        }
        neighborrecycle();
        super.onBackPressed();
     /*   if(null==recordDao){
            recordDao =new ReadRecordEntityDao();
        }*/
        ReadRecord record =new ReadRecord();
            record.setUserId((int)userId);
            record.setBookId(m_ibooknetid);
            record.setOutTime(System.currentTimeMillis());
        //recordDao.updateOutTimeNull(record);

         setResult(Activity.RESULT_OK);
        finish();
    }

    @Override
    public void onDestroy() {
        hideTransLayoutWithoutAnimation();
        mSettingHandler.removeMessages(0);
        mSettingHandler.removeMessages(1);
        m_boncreated = false;
        if (null != m_rqvolley) {
            try {
                m_rqvolley.cancelAll();
            } catch (Exception e) {
            }
            m_rqvolley.stop();
        }
        m_rqvolley = null; //+
     /*   try {
            if (null != m_bmpdictimagefailed) {
                m_bmpdictimagefailed.recycle();
            }
        } catch (Exception e) {
        }
        try {
            if (null != m_bmpdictimagewait) {
                m_bmpdictimagewait.recycle();
            }
        } catch (Exception e) {
        }
        m_bmpdictimagewait = null;
        if (null != m_bmpwordsounds) {
            for (int i = 0; i < m_bmpwordsounds.length; i++) {
                try {
                    m_bmpwordsounds[i].recycle();
                } catch (Exception e) {
                }
                m_bmpwordsounds[i] = null;
            }
        }
        m_bmpwordsounds = null;*/
        if (null != m_lliids) {
            m_lliids.clear();
        }
        m_lliids = null;
        m_iidscount = 0;
        super.onDestroy();
        if (null != m_bdwaitanim) {
            for (int i = 0; i < WAITANIMFRAME_ACCOUNT; i++) {
                if (null != m_bdwaitanim[i]) {
                    try {
                        m_bdwaitanim[i].setCallback(null);
                        m_bdwaitanim[i].getBitmap().recycle();
                    } catch (Exception e) {
                    }
                    m_bdwaitanim[i] = null;
                }
            }
            m_bdwaitanim = null;
        }
        if (null != m_rlreadbook) {
            m_rlreadbook.removeAllViews();
        }
        try {
            m_vpapagesadapter.recycle();


        } catch (Exception e) {
        }
        m_bonWindowFocusChanged = false;

        if (mGalleryAdapter != null) {
            mBottomGallery.setAdapter(null);
            mGalleryAdapter = null;
        }
        if (mGalleryDataList != null) {
            mGalleryDataList.clear();
            mGalleryDataList = null;
        }

        if (mSpeedConvertThread != null) {
            mSpeedConvertThread.stopThread();

            try {
                mSpeedConvertThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mSpeedConvertThread.clearList();
            mSpeedConvertThread = null;

        }
        mSpeedConvertHandler.removeMessages(0);
        mSpeedConvertHandler = null;


    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

    }

    /**
     * 后期需要修改为跳转到对应书架
     */
    private void quitactivityforerrordata() {
        Intent it = null;
        //it = new Intent(ReadBookActivity.this, BookShelfActivity.class);
        it.putExtra(DefaultSettings.BUNDLE_BOOKNETID, m_ibooknetid);
        it.putExtra(DefaultSettings.BUNDLE_BOOKID, m_ibookid);
        it.putExtra(DefaultSettings.BUNDLE_CATALOGID, m_icatalogid);
        it.putExtra(DefaultSettings.BUNDLE_ITEMID, m_iitemid);
        setResult(DefaultSettings.READBOOK_QUITNODATA, it);
        finish();
    }

    private void closekokplaying() {
        try {
            int icur = m_vpbookpage.getCurrentItem();
            NewBookPageView bpv = m_vpapagesadapter.getbookpageview(icur);
            if (null != bpv) {
                bpv.closeplaykokprocess();
            }
            try {
                bpv = m_vpapagesadapter.getbookpageview(icur - 1);
                if (null != bpv) {
                    bpv.closeplaykokprocess();
                }
            } catch (Exception e) {
            }
            try {
                bpv = m_vpapagesadapter.getbookpageview(icur + 1);
                if (null != bpv) {
                    bpv.closeplaykokprocess();
                }
            } catch (Exception e) {
            }
        } catch (Exception e) {
        }
    }

    private void neighborrecycle() {
        try {
            int icur = m_vpbookpage.getCurrentItem();
            try {
                NewBookPageView bpv = m_vpapagesadapter.getbookpageview(icur - 1);
                if (null != bpv) {
                   // bpv.setBackImageBitmap(null);
                    bpv.recycle();
                }
            } catch (Exception e) {
            }
            try {
                NewBookPageView bpv = m_vpapagesadapter.getbookpageview(icur - 2);
                if (null != bpv) {
                    //bpv.setBackImageBitmap(null);
                    bpv.recycle();
                }
            } catch (Exception e) {
            }
            try {
                NewBookPageView bpv = m_vpapagesadapter.getbookpageview(icur + 1);
                if (null != bpv) {
                   // bpv.setBackImageBitmap(null);
                    bpv.recycle();
                }
            } catch (Exception e) {
            }
            try {
                NewBookPageView bpv = m_vpapagesadapter.getbookpageview(icur + 2);
                if (null != bpv) {
                    //bpv.setBackImageBitmap(null);
                    bpv.recycle();
                }
            } catch (Exception e) {
            }
        } catch (Exception e) {
        }
    }


    boolean mStartScroll = false;
    boolean mDuringScroll = false;
    private OnPageChangeListener pagechangelistener = new OnPageChangeListener() {

        @Override
        public void onPageScrollStateChanged(int arg0) {
            //MyLog.d("logautokok onPageScrollStateChanged " + arg0 + " m_bautokok = " + m_bautokok);
            if (arg0 == 1 || arg0 == 2) {
                mStartScroll = true;
            } else if (mStartScroll) {
                if (m_inowpagepos == 0) {
                    showBookMark();
                    m_ireadtype = DefaultSettings.BOOKREADTYPE_READMYSELF;
                }
                mStartScroll = false;
            }


            //to prevent user to click autokok btn during scrolling.
            if (arg0 == 1 || arg0 == 2) {
                mDuringScroll = true;
            } else if (mDuringScroll) {
                mDuringScroll = false;
            }


            closeautokokon();
            if ((arg0 == 1 || arg0 == 2) && (m_inowpagepos == 0) && DefaultSettings.BOOKREADTYPE_READMYSELF == m_ireadtype) {
                getautokokstatus();
                if (m_bautokok) {
                    setautokokstatus(ms_iautokokon);
                } else {
                    setautokokstatus(ms_iautokokoff);
                }
            }

            //MyLog.d("logautokok onPageScrollStateChanged " + arg0 + " m_bautokok = " + m_bautokok);

            if (arg0 == 2) {
                hideTransLayoutWithoutAnimation();
                if (mSpeedBtnShow && m_bnshowspeed.getVisibility() == View.VISIBLE) {
                    changeSettingBarForSpeedBtn(false);
                    mSpeedBtnShow = false;
                    m_bnshowspeed.setVisibility(View.GONE);
                }
            }
            //if (m_bautokok) {

                if (1 == arg0) {
                    m_hreadtomeslippage.removeMessages(0);
                    NewBookPageView bpv = m_vpapagesadapter.getbookpageview(m_inowpagepos);
                    if (null != bpv) {
                        bpv.closeplaykokprocessimmediately();

                    }
                } else if (2 == arg0/* && ConstValues.BOOKREADTYPE_READTOME == m_ireadtype*/) {
                    m_hreadtomeslippage.removeMessages(0);
                    NewBookPageView bpv = m_vpapagesadapter.getbookpageview(m_inowpagepos);
                    if (null != bpv) {
                        bpv.closeplaykokprocessimmediately();
                    }
                } else if (0 == arg0) {
                    if (m_inowpagepos > 0) {
                        autokokforcurrentpage(m_inowpagepos);
                    }
                }
           // }

            mCurrentHotRegionIndex = -1;
            mCurrentHotRegionPageIndex = -1;

/*            if (m_bworddictisshow.get()) {
                backpressclosedictionary(true);
            }*/
            if (m_bworddictisshow.get() > 0) {

                TLog.log("DICTSCROLL  onPageScrollStateChanged " + arg0 + " dict are " + m_bworddictisshow.get());
                backpressclosedictionary(false);
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int ipos) {
            //MyLog.d("logautokok onPageSelected " + ipos + " m_bautokok = " + m_bautokok);

            mStartScroll = false;

            CustomViewPager customvp = (CustomViewPager) m_vpbookpage;
            customvp.setscrollable(true);
            m_llsettingsregion.setVisibility(View.INVISIBLE);
            m_inowpagepos = ipos;
            if (m_inowpagepos == 0) {
                showBookMark();
                m_ireadtype = DefaultSettings.BOOKREADTYPE_READMYSELF;
            } else {
                hideBookMark();
            }
            boolean isQuiz = false;
            Pagesdata pd = getcurrentpagesdataobj(ipos, false);
            m_pdcurrent = pd;

            Pagedata data = m_pdcurrent.getpagedata(m_inowpagepos);
            if (data != null) {
                boolean hasKok = data.hasKok();
                boolean hasPinyin = data.hasPinyin();
                boolean hasAnotherLan = false;
                if (!data.getEnglishPage()){
                    hasAnotherLan = data.hasEn();
                } else {
                    hasAnotherLan = data.hasCn();
                }
                boolean hasTrans = TextUtils.isEmpty(data.getTrans()) ? false : true;
                mTranView.setText(data.getTrans());
                setbookedgeSettingsBarNew(hasKok, hasPinyin, hasAnotherLan, hasTrans, false, data.getEnglishPage());
                m_vwdworddictcontainer.setmEnglishPage(data.getEnglishPage());
            }


            NewBookPageView bpv = m_vpapagesadapter.getbookpageview(ipos);
            if (null != bpv) {
                m_inowpagepos = ipos;
                if (null != m_vpapagesadapter) {
                    TLog.log("Activities  5 recordselectedpage " + m_inowpagepos);
                    m_vpapagesadapter.recordselectedpage(m_inowpagepos);
                }
                if (DefaultSettings.BOOKREADTYPE_READTOME == m_ireadtype) {
                    bpv.setShowPinyinAnotherLan(m_ishowpinyin | m_ishowAnotherLan);
                    bpv.setReadType(DefaultSettings.BOOKREADTYPE_READTOME);
                } else {
                    bpv.setShowPinyinAnotherLan(m_ishowpinyin | m_ishowAnotherLan);
                    bpv.setReadType(DefaultSettings.BOOKREADTYPE_READMYSELF);
                }
                bpv.setSpeed(mCurrentSpeed);
                bpv.setkokplayable(true);
                bpv.setKokCompleted(false); //added by wang qian

                if (!mBottomGalleryClicked) {
                    hidetopFloatbar();
                    hideBottomGallery();
                }
            } else {
                NewQuizView qv = m_vpapagesadapter.getquizview(ipos);
                if (null != qv) {
                    qv.refreshinformation();
                    m_inowpagepos = ipos;
                    showtopFloatbar();
                    hideBottomGallery();
                }
            }


            isQuiz = m_vpapagesadapter.isquizview(ipos);
            if (isQuiz) m_llsettingsregion.setVisibility(View.INVISIBLE);


            if (null != m_tvcurpage && null != m_tvtotalpage && null != m_psds && null != m_pdcurrent) {
                //pagesdata pd = getcurrentpagesdataobj(ipos, false);
                //m_pdcurrent = pd;
                int ipagenumber = m_pdcurrent.getpossiblepagenumber(ipos);
                if (ipagenumber > 0 && null != m_tvtotalpage.getTag()) {
                    m_tvcurpage.setText(ipagenumber + "");
                    ;
                    m_tvtotalpage.setText(((Integer) m_tvtotalpage.getTag()).intValue() + "");
                    m_llpagenumber.setVisibility(View.VISIBLE);

                    m_pagename.setVisibility(View.GONE);
                } else {
                    m_llpagenumber.setVisibility(View.INVISIBLE);
                    m_llsettingsregion.setVisibility(View.INVISIBLE);
                    m_pagename.setVisibility(View.VISIBLE);
                    m_pagename.setText(null);
                    if (isQuiz) {
                        m_pagename.setText(R.string.quiz);
                    } else if (m_pdcurrent.getpossiblepagetype(m_inowpagepos) == DefaultSettings.ms_Json_BookPageType_backover) {
                        m_pagename.setText(R.string.backcover);
                    }
                    else if (m_pdcurrent.getpossiblepagetype(m_inowpagepos) == DefaultSettings.ms_Json_BookPageType_cover) {
                        if (m_pdcurrent.getpossiblepageindex(m_inowpagepos) == 1) {
                            m_pagename.setText(R.string.cover);
                        } else {
                            m_pagename.setText(R.string.cover_two);
                        }
                    } else if (m_pdcurrent.getpossiblepagetype(m_inowpagepos) == DefaultSettings.ms_Json_BookPageType_supplement) {
                        m_pagename.setText(R.string.supplement);
                    } else if (m_pdcurrent.getpossiblepagetype(m_inowpagepos) == DefaultSettings.ms_Json_BookPageType_bookquiz) {
                        m_pagename.setText(R.string.quiz);
                    }
                }
            }

            if (mGalleryAdapter != null && !mBottomGalleryClicked) {
                int selected = mGalleryAdapter.getSelection();
                int offset = selected % mGalleryDataList.size() - m_inowpagepos;
                mBottomGallery.setSelection(selected - offset);
                mGalleryAdapter.setSelection(selected - offset);
            }

            mBottomGalleryClicked = false;


        }
    };

    @Override
    public void inwatingloadpagestatus(boolean bwaiting) {
        boolean bshow = !bwaiting;
        if (bshow) {
            Pagesdata pd = getcurrentpagesdataobj(m_inowpagepos, false);
            m_pdcurrent = pd;
            if (m_pdcurrent != null) {
                Pagedata data = m_pdcurrent.getpagedata(m_inowpagepos);
                if (data != null) {
                    boolean hasKok = data.hasKok();
                    boolean hasPinyin = data.hasPinyin();
                    boolean hasAnotherlan = false;
                    if (!data.getEnglishPage()) {
                        hasAnotherlan = data.hasEn();
                    } else {
                        hasAnotherlan = data.hasCn();
                    }
                    boolean hasTrans = TextUtils.isEmpty(data.getTrans()) ? false : true;
                    mTranView.setText(data.getTrans());
                    setbookedgeSettingsBarNew(hasKok, hasPinyin, hasAnotherlan, hasTrans, false, data.getEnglishPage());
                }
            }
        }
    }



    private void autokokforcurrentpage(int icurpos) {
        try {
            if (null != m_vpapagesadapter && m_inowpagepos >= 0) {
                NewBookPageView bpv = m_vpapagesadapter.getbookpageview(m_inowpagepos);
                if (null != bpv) {
                    if (m_bautokok) {
                        if (System.currentTimeMillis() - m_llastscrolltime < 600) {
                            // to avoid multiple sound once pageview is scrolled too quickly
                            if (null != m_hscrollwaitautokok) {
                                Message msg = new Message();
                                msg.what = MSG_DELAYSTARTAUTOKOK;
                                msg.arg1 = icurpos;
                                m_hscrollwaitautokok.sendMessageDelayed(msg, 600);
                            }
                        } else {
                            if (bpv.setautokok(m_bautokok, icurpos)) {
                                setautokokstatus(ms_iautokokon);
                            } else {
                                if (DefaultSettings.BOOKREADTYPE_READTOME == m_ireadtype) {
                                    try {
                                        Pagesdata psd = getcurrentpagesdataobj(m_inowpagepos, true);
                                        if (null != psd) {
                                            Pagedata pd = psd.getpagedata(m_inowpagepos);
                                            if (null != pd) {
                                                if (DefaultSettings.ms_Json_BookPageType_page != pd.getpageType()) {
                                                    if (!TextUtils.isEmpty(pd.getTitleMp3())) {

                                                    } else {
                                                        m_hreadtomeslippage.sendEmptyMessageDelayed(0, 2500);
                                                    }
                                                } else {
                                                    KokRegion kr = pd.getKokRegion();
                                                    if (null == kr) {
                                                        m_hreadtomeslippage.sendEmptyMessageDelayed(0, 2500);
                                                    } else {
                                                        String smp3[] = kr.getallaudiofilepathes();
                                                        if (null == smp3 || smp3.length <= 0) {
                                                            m_hreadtomeslippage.sendEmptyMessageDelayed(0, 2500);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    } catch (Exception e) {
                                        TLog.error("NewReadBookActivity : autokokforcurrentpage : icurpos = " + icurpos + " : e : " + e);
                                    }

                                }
                            }
                        }
                        m_llastscrolltime = System.currentTimeMillis();
                    }
                }
            }
        } catch (Exception e) {
        }
    }

    private void setbooktopFloatBar(String sbookname, int ibookpages) {
        m_rlbooktopfloatbar = (RelativeLayout) findViewById(R.id.rl_booktopmenubar);

        floatbarhideprocess();

        m_bntobookshelf = (Button) findViewById(R.id.bn_tobookshelf);

        m_bntobookshelf.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                UmsAgent.onEvent(ReadBookActivity.this, "Page_clk_btn_back");
                backpressclosedictionary(false);
                ReadBookActivity.this.onBackPressed();
            }
        });

        m_tvbookname = (TextView) findViewById(R.id.tv_bookname);
        m_tvbookname.setTextColor(DefaultSettings.BOOKTOPMENUBAR_TITLEFONT_COLOR);

        m_tvbookname.setText(sbookname);

        m_llpagenumber = (LinearLayout) findViewById(R.id.ll_pagenumber);

        FrameLayout.LayoutParams rll = (FrameLayout.LayoutParams) m_llpagenumber.getLayoutParams();
        if (null != rll) {
            //rll.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            //rll.addRule(RelativeLayout.CENTER_VERTICAL);
            rll.rightMargin = getscaledsizeXdirection(BOOKTOPMENUBAR_BOOKSETTINGSMARGIN);
            m_llpagenumber.setLayoutParams(rll);
        }

        m_pagename = (TextView) findViewById(R.id.page_name);

        rll = (FrameLayout.LayoutParams) m_pagename.getLayoutParams();
        if (null != rll) {
            //rll.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            //rll.addRule(RelativeLayout.CENTER_VERTICAL);
            rll.rightMargin = getscaledsizeXdirection(BOOKTOPMENUBAR_BOOKSETTINGSMARGIN);
            m_pagename.setLayoutParams(rll);
            m_pagename.setTextColor(DefaultSettings.PAGESELECTION_FOOTFONT_CURPAGE_COLOR);
        }


        m_tvcurpage = (TextView) findViewById(R.id.tv_curpage);
        m_tvpagecut = (TextView) findViewById(R.id.tv_cut);
        m_tvtotalpage = (TextView) findViewById(R.id.tv_totalpage);
        m_tvcurpage.setTextColor(DefaultSettings.PAGESELECTION_FOOTFONT_CURPAGE_COLOR);
        m_tvpagecut.setTextColor(DefaultSettings.PAGESELECTION_FOOTFONT_CUT_COLOR);
        m_tvtotalpage.setTextColor(DefaultSettings.PAGESELECTION_FOOTFONT_TOTALPAGE_COLOR);

        m_tvtotalpage.setTag(ibookpages);
    }

    private void setbookedgeSettingsBarNew(boolean bhaskok, boolean bhaspinyin, boolean bhasAnotherLan, boolean bhastranslation, boolean init, boolean isEngishBook) {
        boolean bshow = bhaskok | bhaspinyin | bhasAnotherLan | bhastranslation;
        if (bshow && DefaultSettings.BOOKREADTYPE_READMYSELF == m_ireadtype) {
            m_llsettingsregion.setVisibility(View.VISIBLE);
        } else {
            m_llsettingsregion.setVisibility(View.INVISIBLE);
            return;
        }

        if (!isEngishBook) {
            m_bnshowAnotherLan.setBackgroundResource(R.drawable.reader_en_btn_bg);
        } else {
            m_bnshowAnotherLan.setBackgroundResource(R.drawable.reader_cn_btn_bg);
        }
        int btn_width_height = (int) getResources().getDimension(R.dimen.booksetting_btn_width);
        int inteval = (int) getResources().getDimension(R.dimen.booksetting_btn_inteval);

        int btn_num = (bhaskok ? 1 : 0) + (bhaspinyin ? 1 : 0) + (bhasAnotherLan ? 1 : 0) + (bhastranslation ? 1 : 0) + 1;
        int height = btn_width_height * btn_num + inteval * (btn_num - 1);

        int top_height = (int) getResources().getDimension(R.dimen.topbar_height)
                + (int) getResources().getDimension(R.dimen.booksetting_btn_margin);

        if (m_bnbooksettings.isSelected()) {
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) m_llsettingsregion.getLayoutParams();
            if (lp.leftMargin == 0 || init) {
                lp.leftMargin = mScreenWidth - btn_width_height - (int) getResources().getDimension(R.dimen.booksetting_btn_margin);
                lp.topMargin = (mScreenHeight - height) / 2;
            } else {
                int old_btn_num = ((m_bnautokok.getVisibility() == View.VISIBLE) ? 1 : 0)
                        + ((m_bnshowAnotherLan.getVisibility() == View.VISIBLE) ? 1 : 0)
                        + ((m_bnshowpinyin.getVisibility() == View.VISIBLE) ? 1 : 0)
                        + ((m_bnshowtrans.getVisibility() == View.VISIBLE) ? 1 : 0) + 1;
                int old_height = btn_width_height * old_btn_num + inteval * (old_btn_num - 1);


                if (old_height > height) {
                    lp.topMargin += (old_height - height);
                } else if (old_height < height) {
                    int delta = height - old_height;
                    if ((lp.topMargin - delta) < top_height) {
                        lp.topMargin = top_height;
                    } else {
                        lp.topMargin -= delta;
                }
                } else {
                }
            }
            m_llsettingsregion.setLayoutParams(lp);
        }

        m_bnautokok.setVisibility(bhaskok ? View.VISIBLE : View.GONE);
        m_bnshowAnotherLan.setVisibility(bhasAnotherLan ? View.VISIBLE : View.GONE);
        m_bnshowpinyin.setVisibility(bhaspinyin ? View.VISIBLE : View.GONE);
        m_bnshowtrans.setVisibility(bhastranslation ? View.VISIBLE : View.GONE);
        m_bnbooksettings.setVisibility(bshow ? View.VISIBLE : View.GONE);

        if (bhaspinyin) {
            m_bnshowpinyin.setSelected(m_ishowpinyin > 0);
        }
        if (bhasAnotherLan) {
            m_bnshowAnotherLan.setSelected(m_ishowAnotherLan > 0);
        }
        if (bhaskok) {
            m_bnautokok.setBackgroundDrawable(m_bautokok ? m_dwautokokon[0] : m_dwautokokoff);
        }
        if (bhastranslation) {
            m_bnshowtrans.setSelected(m_ishowthrans > 0);
        }

    }

    private void changeSettingBarForSpeedBtn(boolean showSpeedBtn) {
        RelativeLayout.LayoutParams rp = (RelativeLayout.LayoutParams) m_llsettingsregion.getLayoutParams();
        if (rp != null && m_llsettingsitems.getVisibility() == View.VISIBLE) {
            if (m_bnshowspeed.getVisibility() == View.VISIBLE && !showSpeedBtn) {
                rp.topMargin += (getResources().getDimension(R.dimen.booksetting_speed_btn_height)
                        + getResources().getDimension(R.dimen.booksetting_btn_inteval));

            } else if (m_bnshowspeed.getVisibility() == View.GONE && showSpeedBtn) {
                int newtopmargin = rp.topMargin - (int)(getResources().getDimension(R.dimen.booksetting_speed_btn_height)
                                + getResources().getDimension(R.dimen.booksetting_btn_inteval));
                int top_bar_space = (int) getResources().getDimension(R.dimen.topbar_height)
                        + (int) getResources().getDimension(R.dimen.booksetting_btn_margin);
                rp.topMargin = newtopmargin;
                if (newtopmargin < top_bar_space) rp.topMargin = top_bar_space;
                m_llsettingsregion.setLayoutParams(rp);
            }
        }
    }

    private void initbookedgeSettingsBar() {
        m_llsettingsregion = (LinearLayout) findViewById(R.id.ll_lsettingsregion);
        m_llsettingsitems = (LinearLayout) findViewById(R.id.ll_lsettingsitems);

        m_llsettingsregion.setVisibility(View.INVISIBLE);

        m_bnbooksettings = (TouchMoveButton) findViewById(R.id.bn_lbooksettings);
        m_bnbooksettings.setSelected(true);
        m_bnbooksettings.setParentLayout(m_llsettingsregion);
        m_bnbooksettings.setOnClicked(this);
        m_bnbooksettings.setHandler(mSettingHandler);

        int top_height = (int) getResources().getDimension(R.dimen.topbar_height);
        int bottom_height = (int) getResources().getDimension(R.dimen.bottomgallery_margin) * 2
                + (int) getResources().getDimension(R.dimen.thumbnail_height);
        m_bnbooksettings.setTopBottomView(top_height, bottom_height);


        m_bnbooksettings.setSceenSize(mScreenWidth, mScreenHeight);

        m_bnautokok = (Button) findViewById(R.id.bn_lautokok);
        m_bnshowpinyin = (Button) findViewById(R.id.bn_lshowpinyin);
        m_bnshowAnotherLan = (Button) findViewById(R.id.bn_lshowanotherlan);
        m_bnshowtrans = (Button) findViewById(R.id.bn_ltrans);
        m_bnshowspeed = (Button)findViewById(R.id.bn_lspeed);
        m_bnshowspeed.setTag(mCurrentSpeed);
        m_bnshowspeed.setBackgroundResource(R.drawable.book_icon_speed_middle);

        m_bnautokok.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
               // MyLog.d("logautokok onClick");

                if (mDuringScroll) {
                    //MyLog.d("logautokok onClick return");
                    return;
                }
                UmsAgent.onEvent(ReadBookActivity.this, "Toolbar_read_clk");
                boolean bautokok = false;
               // MyLog.d("logautokok onClick " + m_bautokok);
                if (!m_bautokok) {
                    bautokok = true;
                } else {
                    Integer ii = (Integer) m_bnautokok.getTag();
                    if (null != ii) {
                        switch (ii.intValue()) {
                            case ms_iautokokon:
                                bautokok = false;
                                break;
                            case ms_iautokokwait:
                            case ms_iautokokoff:
                                bautokok = true;
                                break;
                            default:
                                bautokok = false;
                                break;
                        }
                    } else {
                        bautokok = false;
                    }
                }
                int icur = m_vpbookpage.getCurrentItem();
                if (icur >= 0) {
                    NewBookPageView bpv = m_vpapagesadapter.getbookpageview(icur);
                    if (null != bpv) {

                        boolean support_speed = false;
                        synchronized (mSpeedConvertState) {
                            support_speed = mSpeedConvertState[icur];
                        }

                        if (bautokok) {
                            UmsAgent.onEvent(ReadBookActivity.this, "Toolbar_read_pause");
                            if (mCurrentHotRegionPageIndex >= 0 || mCurrentHotRegionIndex >= 0) {
                                bpv.closeplaykokprocessimmediately();
                            }
                            if (bpv.setautokok(bautokok, icur)) {
                                m_bautokok = bautokok;
                                setautokokstatus(ms_iautokokon);
                            }
                            mCurrentHotRegionPageIndex = -1;
                            mCurrentHotRegionIndex = -1;
                            //postcloseworddictdescview();

                            if (support_speed && !mSpeedBtnShow) {
                                changeSettingBarForSpeedBtn(true);
                                m_bnshowspeed.setVisibility(View.VISIBLE);
                                mSpeedBtnShow = true;
                            }
                        } else {
                            UmsAgent.onEvent(ReadBookActivity.this, "Toolbar_read_off");
                            m_bautokok = bautokok;
                            bpv.requestClosePlaykokProcess();
                           // bpv.closeplaykokprocess();
                            //bpv.setautokok(bautokok, icur);
                            setautokokstatus(ms_iautokokoff);


                            if (support_speed) {

                                changeSettingBarForSpeedBtn(false);
                                mSpeedBtnShow = false;
                                m_bnshowspeed.setVisibility(View.GONE);
                            }
                        }
                    } else {
                        if (null != m_vpapagesadapter.getquizview(icur)) {
                            m_bautokok = bautokok;
                            setautokokstatus(m_bautokok ? ms_iautokokon : ms_iautokokwait);
                        }
                    }
                }

                /*
                SharedPreferences settings = getSharedPreferences(KIDSIREADSETTINGS, MODE_PRIVATE);
                SharedPreferences.Editor editor = settings.edit();
                if (ConstValues.BOOKREADTYPE_READMYSELF == m_ireadtype) {
                    editor.putBoolean(SETTINGSAUTOKOK + m_ibookid, m_bautokok);
                }*/
            }
        });



        m_bnshowspeed.setOnClickListener(new Button.OnClickListener(){
            @Override
            public void onClick(View v) {
                int oldspeed = mCurrentSpeed;
                switch(mCurrentSpeed) {
                    case SPEED_NORMAL:
                        if (mOldSpeed == SPEED_FAST) {
                            mCurrentSpeed = SPEED_SLOW;
                            m_bnshowspeed.setBackgroundResource(R.drawable.reader_speed_slow);
                        } else {
                            mCurrentSpeed = SPEED_FAST;
                            m_bnshowspeed.setBackgroundResource(R.drawable.reader_speed_fast);
                        }
                        break;
                    case SPEED_FAST:
                        mCurrentSpeed = SPEED_NORMAL;
                        m_bnshowspeed.setBackgroundResource(R.drawable.reader_speed_middle);
                        break;
                    case SPEED_SLOW:
                        mCurrentSpeed = SPEED_NORMAL;
                        m_bnshowspeed.setBackgroundResource(R.drawable.reader_speed_middle);
                        break;
                }
                mOldSpeed = oldspeed;

                closeautokokon();
                int icur = m_vpbookpage.getCurrentItem();
                if (icur >= 0) {
                    NewBookPageView bpv = m_vpapagesadapter.getbookpageview(icur);
                    if (null != bpv) {
                        bpv.setSpeed(mCurrentSpeed);
                        if (m_bautokok) {
                            bpv.closeplaykokprocess();
                            if (bpv.setautokok(m_bautokok, icur)) {
                                setautokokstatus(ms_iautokokon);
                            }
                        }
                    }
                }
            }
        });

        m_bnshowpinyin.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                UmsAgent.onEvent(ReadBookActivity.this, "Toolbar_py_clk");
                if (m_ishowpinyin > 0) {
                    m_ishowpinyin = 0;
                    UmsAgent.onEvent(ReadBookActivity.this, "Toolbar_py_off");
                } else {
                    m_ishowpinyin = 1;
                    UmsAgent.onEvent(ReadBookActivity.this, "Toolbar_py_on");
                }
                m_bnshowpinyin.setSelected(m_ishowpinyin > 0);
                int icur = m_vpbookpage.getCurrentItem();
                if (icur >= 0) {
                    NewBookPageView bpv = m_vpapagesadapter.getbookpageview(icur);
                    if (null != bpv) {
                        bpv.setShowPinyinAnotherLan(m_ishowpinyin | m_ishowAnotherLan);
                    }
                }
            }
        });

        m_bnshowAnotherLan.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (m_ishowAnotherLan > 0) {
                    m_ishowAnotherLan = 0;
                    UmsAgent.onEvent(ReadBookActivity.this, "Toolbar_en_off");
                } else {
                    m_ishowAnotherLan = 2;
                    UmsAgent.onEvent(ReadBookActivity.this, "Toolbar_en_on");
                }
                m_bnshowAnotherLan.setSelected(m_ishowAnotherLan > 0);
                int icur = m_vpbookpage.getCurrentItem();
                if (icur >= 0) {
                    NewBookPageView bpv = m_vpapagesadapter.getbookpageview(icur);
                    if (null != bpv) {
                        bpv.setShowPinyinAnotherLan(m_ishowpinyin | m_ishowAnotherLan);
                    }
                }
            }
        });

        m_bnshowtrans.setOnClickListener(new Button.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                if (m_ishowthrans > 0) {
                    m_ishowthrans = 0;
                    hideTransLayout();
                } else {
                    m_ishowthrans = 1;
                    UmsAgent.onEvent(ReadBookActivity.this, "Toolbar_trans_clk");
                    if (m_bworddictisshow.get() > 0) {
                        backpressclosedictionary(true);
                }
                    showTransLayout(m_pdcurrent.getpagedata(m_inowpagepos).getTrans());
                }
                m_bnshowtrans.setSelected(m_ishowthrans > 0);
            }
        });

        initautokokbackgroundbitmap();

        Pagedata data = m_pdcurrent.getpagedata(m_inowpagepos);
        if (data != null) {
            boolean hasKok = data.hasKok();
            boolean hasPinyin = data.hasPinyin();
            boolean hasAnotherLan = false;
            if (!data.getEnglishPage()) {
                hasAnotherLan = data.hasEn();
            } else {
                hasAnotherLan = data.hasCn();
            }
            boolean hasTrans = TextUtils.isEmpty(data.getTrans()) ? false : true;
            setbookedgeSettingsBarNew(hasKok, hasPinyin, hasAnotherLan, hasTrans, true, data.getEnglishPage());
        } else {
            m_llsettingsregion.setVisibility(View.INVISIBLE);
    }

    }
    // 0, autokok is playing; 1, autokok is stopped; 2, playkok is waiting
    private void setautokokstatus(int istatus) {
        try {
            m_bnautokok.setTag(istatus);
        } catch (Exception e) {
        }
        try {
            switch (istatus) {
                case ms_iautokokon:        // 0
                    startautokokon();
                    break;
                case ms_iautokokoff:    // 1
                    m_bnautokok.setBackgroundDrawable(m_dwautokokoff);
                    closeautokokon();
                    break;
                case ms_iautokokwait:    // 2
                    m_bnautokok.setBackgroundDrawable(m_dwautokokwait);
                    closeautokokon();
                    break;
            }
        } catch (Exception e) {
        }
    }

    private void startautokokon() {
        m_tmkok = new Timer();
        m_ttkoktask = new TimerTask() {
            int itimercount = 0;

            @Override
            public void run() {
                Message msg = new Message();
                msg.what = 0;
                msg.arg1 = itimercount;
                if (0 == itimercount) {
                    itimercount++;
                } else {
                    itimercount = 0;
                }
                m_hshowkokanim.sendMessage(msg);
            }
        };
        m_tmkok.schedule(m_ttkoktask, 0, 500);
    }

    private Handler m_hshowkokanim = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != m_dwautokokon && m_bautokok && null != m_tmkok) {
                m_bnautokok.setBackgroundDrawable(m_dwautokokon[msg.arg1]);
            }
        }
    };

    private void closeautokokon() {

        try {
            if (null != m_tmkok) {
                m_tmkok.cancel();
                m_tmkok = null;
            }
            if (null != m_ttkoktask) {
                m_ttkoktask.cancel();
                m_ttkoktask = null;
            }
        } catch (Exception e) {
        }
    }

    private void getautokokstatus() {
        if (DefaultSettings.BOOKREADTYPE_READMYSELF == m_ireadtype) {
            m_bautokok = false;
        } else {
            m_bautokok = true;
        }
    }



    private void getenglishstatus() {
        m_ishowAnotherLan = 2;
    }

    private int getlastreadinnerpage() {
        return PreferenceUtils.getLastReadInnerPage(context,m_ibookid, userId+"");
    }

    private void savequitstatus() {
        int isavedinnerpage = 0;
        try {
            isavedinnerpage = m_vpbookpage.getCurrentItem();
        } catch (Exception e) {
        }

        if (DefaultSettings.BOOKREADTYPE_READMYSELF == m_ireadtype) {
            PreferenceUtils.saveReadBookMode(context, m_ibookid, userId+"", false);
        } else {
            PreferenceUtils.saveReadBookMode(context, m_ibookid, userId+"", true);
        }

        PreferenceUtils.saveLastReadInnerPage(context, m_ibookid, userId + "", isavedinnerpage);

    }

    @Override
    public void playkokcompleted(boolean toflip) {
        if (m_bautokok) {
            setautokokstatus(ms_iautokokwait);
            autodoreadtometypebookpage(toflip);
        } else {
            setautokokstatus(ms_iautokokoff);
        }

        if (mSpeedBtnShow == true && m_bnshowspeed.getVisibility() == View.VISIBLE) {
            changeSettingBarForSpeedBtn(false);
            m_bnshowspeed.setVisibility(View.GONE);
            mSpeedBtnShow = false;
        }

        mCurrentHotRegionIndex = -1;
        mCurrentHotRegionPageIndex = -1;
    }

    @Override
    public void autokokcurrentpagecompleted() {
        setautokokstatus(ms_iautokokwait);
        autodoreadtometypebookpage(true);
    }

    @Override
    public int getpinyinenglishshow() {
        return (m_ishowpinyin | m_ishowAnotherLan);
    }

    @Override
    public void postworddictsound(int bookid, int inetid, int iviewid, String sbaseword, StringDouble[] sdSounds) {
        if (m_bworddictisshow.get() > 0) {
            Integer ii = (Integer) m_vwdworddictcontainer.getTag();
            if (null != ii && ii.intValue() == iviewid) {
                m_vwdworddictcontainer.informworddictsoundfileok(bookid, inetid, iviewid, sbaseword, sdSounds);
            }
        }
    }

    @Override
    public void postcloseworddictdescview() {
        if (null != m_hshowworddict) {
            Message msg = new Message();
            msg.what = MSG_HIDEDICTVIEW;
            m_hshowworddict.sendMessage(msg);
        }
    }


    private void showWordDictView() {
        m_bworddictisshow.set(1);

        int x = mWordDictShowFromX;
        int y = mWordDictShowFromY;
        RelativeLayout.LayoutParams rp = (RelativeLayout.LayoutParams) m_vwdworddictcontainer.getLayoutParams();
        if (rp != null) {
            x -= rp.leftMargin;
            y -= rp.topMargin;
        }


        mWordDictShowAnim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f,
                Animation.ABSOLUTE, x, Animation.ABSOLUTE, y);
        mWordDictShowAnim.setDuration(500);
        mWordDictShowAnim.setAnimationListener(new AnimationListener() {
                                                   @Override
                                                   public void onAnimationStart(Animation animation) {
                                                       TLog.log("DICTSCROLL  onAnimationStart " + m_bworddictisshow.get());
                                                       if (m_bworddictisshow.get() == 1) {
                                                           //m_vwdworddictcontainer.setVisibility(View.VISIBLE);
                                                       }
                                                   }

                                                   @Override
                                                   public void onAnimationEnd(Animation animation) {
                                                       TLog.log("DICTSCROLL  onAnimationEnd " + m_bworddictisshow.get());
                                                       if (m_bworddictisshow.get() == 1) {
                                                           m_bworddictisshow.incrementAndGet();
                                                           mWordDictShowAnim = null;
                                                           //m_vwdworddictcontainer.setVisibility(View.VISIBLE);
                                                       }
                                                   }

                                                   @Override
                                                   public void onAnimationRepeat(Animation animation) {
                                                   }
                                               }
        );
        if (m_bworddictisshow.get() == 1) {
            m_vwdworddictcontainer.setVisibility(View.VISIBLE);
        }
        m_vwdworddictcontainer.setAnimation(mWordDictShowAnim);
        mWordDictShowAnim.startNow();


    }
    private void hideWordDictView() {
        m_bworddictisshow.set(-1);

        int x = mWordDictShowFromX;
        int y = mWordDictShowFromY;
        RelativeLayout.LayoutParams rp = (RelativeLayout.LayoutParams) m_vwdworddictcontainer.getLayoutParams();
        if (rp != null) {
            x  -= rp.leftMargin;
            y  -= rp.topMargin;
        }



        mWordDictHideAnim = new ScaleAnimation(1.0f, 0.0f, 1.0f, 0.0f,
                Animation.ABSOLUTE,x, Animation.ABSOLUTE, y);
        mWordDictHideAnim.setDuration(500);
        mWordDictHideAnim.setAnimationListener(new AnimationListener() {
                                                   @Override
                                                   public void onAnimationStart(Animation animation) {
                                                       //m_vwdworddictcontainer.setVisibility(View.VISIBLE);
                                                   }

                                                   @Override
                                                   public void onAnimationEnd(Animation animation) {
                                                       if (m_bworddictisshow.get() == -1) {
                                                           m_bworddictisshow.incrementAndGet();
                                                           m_vwdworddictcontainer.setVisibility(View.GONE);
                                                           mWordDictHideAnim = null;
                                                       }
                                                       if (m_bworddictisshow.get() <= 0) {
                                                           liquidateWorddictView();
                                                           clearworddictdescviewid();
                                                           if (null != m_wddworddictdata) {
                                                               m_wddworddictdata.clear();
                                                               m_wddworddictdata = null;
                                                           }
                                                       }
                                                   }

                                                   @Override
                                                   public void onAnimationRepeat(Animation animation) {
                                                   }
                                               }
        );
        //m_vwdworddictcontainer.setVisibility(View.VISIBLE);

        //m_vwdworddictcontainer.setAnimation(mWordDictHideAnim);
        //mWordDictHideAnim.startNow();
        m_vwdworddictcontainer.startAnimation(mWordDictHideAnim);

    }

    private void hideWordDictViewWithoutAnim() {
        TLog.log("DICTSCROLL  hideWordDictViewWithoutAnim " + m_bworddictisshow.get());
        m_bworddictisshow.set(0);

        if (mWordDictShowAnim != null) {
            mWordDictShowAnim.cancel();
            mWordDictShowAnim = null;
        }
        m_vwdworddictcontainer.setAnimation(null);
        m_vwdworddictcontainer.setVisibility(View.GONE);

        liquidateWorddictView();
        clearworddictdescviewid();
        if (null != m_wddworddictdata) {
            m_wddworddictdata.clear();
            m_wddworddictdata = null;
        }
    }

    @Override
    public void getdictionarydescription(int ibookid, int ibooknetiId, String sdictword, String sdictpinyin, int touch_x, int touch_y) {
        if (TextUtils.isEmpty(sdictword) || TextUtils.isEmpty(sdictpinyin)) {
            return;
        }
        int iviewId = ReadBookActivity.getexclusivetagId();
        if (iviewId >= 0 && null != m_vwdworddictcontainer) {
            mWordDictShowFromX = touch_x;
            mWordDictShowFromY = touch_y;
            m_vwdworddictcontainer.setTag(iviewId);
            m_vwdworddictcontainer.showworddictionarydata(m_rqvolley, ibookid, ibooknetiId, sdictword, sdictpinyin, iviewId,
                    "and", android.os.Build.VERSION.SDK_INT, m_sappver);
            if (m_bworddictisshow.get() <= 0) {
                //m_vwdworddictcontainer.setVisibility(View.VISIBLE);
                resetWordDictViewPos();
                showWordDictView();
            }
            //m_rlreadbook.bringChildToFront(m_vwdworddictcontainer);

            m_ishowthrans = 0;
            m_bnshowtrans.setSelected(m_ishowthrans > 0);
            hideTransLayout();
        }
    }

    @Override
    public void getDictionaryEnDescription(int ibookid, int ibooknetid, EnDictData data, int touch_x, int touch_y) {
        if (TextUtils.isEmpty(data.mJansonPhrase) || data.mPhraseIndex < 0) {
            return;
        }
        //m_bworddictisshow.set(true);
        int iviewId = ReadBookActivity.getexclusivetagId();
        if (iviewId >= 0 && null != m_vwdworddictcontainer) {
            mWordDictShowFromX = touch_x;
            mWordDictShowFromY = touch_y;
            m_vwdworddictcontainer.setTag(iviewId);
            m_vwdworddictcontainer.showEnWordDictionaryData(m_rqvolley, ibookid, ibooknetid, data, iviewId,
                    "and", android.os.Build.VERSION.SDK_INT, m_sappver);
            if (m_bworddictisshow.get() <= 0) {
                //m_vwdworddictcontainer.setVisibility(View.VISIBLE);
                resetWordDictViewPos();
                showWordDictView();
            }
            //m_rlreadbook.bringChildToFront(m_vwdworddictcontainer);

            m_ishowthrans = 0;
            m_bnshowtrans.setSelected(m_ishowthrans > 0);
            hideTransLayout();
        }
    }

    // close dictionary-view, and, show top-bar if possible
    @Override
    public void bookpageviewonTouch(int iaction, int ix, int iy, boolean scaled) {
        if (m_bworddictisshow.get() > 0) {
            postcloseworddictdescview();
        } else
        if (m_transShow.get() > 0) {
            m_ishowthrans = 0;
            m_bnshowtrans.setSelected(m_ishowthrans > 0);
            hideTransLayout();
        } else
        if (MotionEvent.ACTION_POINTER_ID_SHIFT == iaction && -9999 == ix && -9999 == iy) {
            if (0 == m_ifloatbarshow.get() && !scaled) {
                showtopFloatbar();
            } else if (2 == m_ifloatbarshow.get()) {
                hidetopFloatbar();
            }
            if (0 == m_bottomGalleryShow.get() && !scaled) {
                showBottomGallery();
            } else if (2 == m_bottomGalleryShow.get()) {
                hideBottomGallery();
            }
        }
    }

    public void bookpageviewonTouchMove(int isx, int isy, int iex, int iey) {
        int ideta = iey - isy;
        int iskip = getscaledsizeYdirection(BOOKTOPMENUBAR_HEIGHT);
        if (Math.abs(ideta) > iskip) {
            if (ideta > 0 && isy < 3 * iskip) {
                showtopFloatbar();
                showBottomGallery();
            } else if (iey < 3 * iskip) {
                hidetopFloatbar();
                hideBottomGallery();

                m_ishowthrans = 0;
                m_bnshowtrans.setSelected(m_ishowthrans > 0);
                hideTransLayout();
            }
        }
    }

    private void initworddictdescview() {

        m_vwdworddictcontainer = (NewViewWordDictdesc) findViewById(R.id.vwd_worddictcontainer);

        resetWordDictViewPos();

        Pagedata data = m_pdcurrent.getpagedata(m_inowpagepos);
        m_vwdworddictcontainer.setVisibility(View.GONE);
        m_vwdworddictcontainer.setScreenSize(mScreenWidth, mScreenHeight);
        m_vwdworddictcontainer.findviews(
                m_sbd_dictimgprefixurl, m_sbd_dictsoundprefixurl,
                this, mSceenDensity,data.getEnglishPage());

    }


    private void resetWordDictViewPos() {
        RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) m_vwdworddictcontainer.getLayoutParams();
        if (null != rlp) {

            int width = (int) getResources().getDimension(R.dimen.worddict_layout_width);
            int height = (int) getResources().getDimensionPixelOffset(R.dimen.worddict_layout_height);
            rlp.leftMargin = (mScreenWidth - width) / 2;
            rlp.topMargin = (mScreenHeight - height) / 2;
            rlp.width = width;
            rlp.height = height;
            m_vwdworddictcontainer.setLayoutParams(rlp);
        }
    }

    private Handler m_hbookreaderReceiver = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (DefaultSettings.Msg_BOOKPARTREADYFORREAD == msg.what) {
                // ipartnumber starts from 1
                int ipartnumber = msg.arg1;
                if (null != m_psds && ipartnumber > 0 && ipartnumber <= m_psds.length && null != m_sspartssers) {
                    try {
                        m_psds[ipartnumber - 1] = FileUtil.unserializebookpartpage(m_sspartssers[ipartnumber - 1]);
                        if (null != m_psds[ipartnumber - 1]) {
                            checkandupdatelandscapebookpagesdata(m_psds[ipartnumber - 1]);
                            m_vpapagesadapter.updatepagesdata(m_psds[ipartnumber - 1], ipartnumber - 1, m_inowpagepos, m_bautokok);
                        }
                    } catch (Exception e) {
                    }
                }
            } else if (DefaultSettings.Msg_BOOKPARTDOWNLAODERROR == msg.what) {
                int ibooknetid = msg.arg1;
                if (ibooknetid == m_ibooknetid) {
                    if (null != m_vpapagesadapter) {
                        m_vpapagesadapter.informbookdownloaderrorresolved(false);
                    }
                }
            }
        }
    };

    private void checkandupdatelandscapebookpagesdata(Pagesdata psd) {
        if (null != psd && m_bisbooklandscape && !psd.positioniscalculated()) {
            if (null != m_rlreadbook) {
                int iw = m_rlreadbook.getWidth();
                int ih = m_rlreadbook.getHeight();
                if (iw > 0 && ih > 0) {
                    psd.updatecharacterposition(iw, ih);
                    updateseerializedbookpartpage(psd);
                }
            }
        }
    }

    private void setScreenOrientation(int iorientation) {
        if (DefaultSettings.BOOK_ORIENTATION_LANDSCAPE == iorientation) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            m_bisbooklandscape = true;
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            m_bisbooklandscape = false;
        }
    }

    private Handler m_hscrollwaitautokok = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_DELAYSTARTAUTOKOK:
                    if (msg.arg1 == m_inowpagepos) {
                        NewBookPageView bpv = m_vpapagesadapter.getbookpageview(m_inowpagepos);
                        if (null != bpv && m_bautokok) {
                            if (bpv.setautokok(m_bautokok, msg.arg1)) {
                            } else {
                                setautokokstatus(ms_iautokokoff);
                            }
                        }
                    }
                    break;
                case MSG_PAGEOPENSTARTAUTOKOK:
                    if (msg.arg1 == m_inowpagepos) {
                        NewBookPageView bpv = m_vpapagesadapter.getbookpageview(m_inowpagepos);
                        if (null != bpv && m_bautokok) {
                            if (bpv.setautokok(m_bautokok, m_inowpagepos)) {
                                setautokokstatus(ms_iautokokon);
                            } else {
                                setautokokstatus(ms_iautokokoff);
                            }
                        }
                    }
            }
        }
    };


    private void initautokokbackgroundbitmap(/*int iwidth, int iheight*/) {
        if (null == m_dwautokokon) {
            m_dwautokokon = new Drawable[2];
            m_dwautokokon[0] = getResources().getDrawable(R.drawable.book_icon_speaker_play_low);
            m_dwautokokon[1] = getResources().getDrawable(R.drawable.book_icon_speaker_play);
            m_dwautokokoff = getResources().getDrawable(R.drawable.reader_speaker_stop);
            m_dwautokokwait = getResources().getDrawable(R.drawable.reader_speaker_pause);
        }
    }

    private boolean checkscreenbasicinfoexisted(Pagesdata pd) {
        m_dsi = PreferenceUtils.readdevicescreenbasicinfo(this, m_bisbooklandscape);
        boolean b1 = (m_dsi.m_iScreenWidth > 200 && m_dsi.m_iScreenHeight > 200);
        boolean b2 = false;
        if (null != pd) {
            b2 = pd.positioniscalculated();
        }
        return b1 && b2;
    }

    private void updatescreenbasicinfo(int iScreenWidth, int iScreenHeight, boolean bisbooklandscape) {
        m_dsi = PreferenceUtils.readdevicescreenbasicinfo(this, bisbooklandscape);
        m_dsi.m_iScreenWidth = iScreenWidth;
        m_dsi.m_iScreenHeight = iScreenHeight;
        SharedPreferences settings = getSharedPreferences(PreferenceUtils.ms_sp_wawayayareader, MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        String skey = m_bisbooklandscape ? PreferenceUtils.ms_sp_wawayayareader_horscreenwidth : PreferenceUtils.ms_sp_wawayayareader_screenwidth;
        editor.putInt(skey, m_dsi.m_iScreenWidth);
        skey = m_bisbooklandscape ? PreferenceUtils.ms_sp_wawayayareader_horscreenheight : PreferenceUtils.ms_sp_wawayayareader_screenheight;
        editor.putInt(skey, m_dsi.m_iScreenHeight);
        editor.commit();
    }

    private void updateseerializedbookpartpage(Pagesdata pd) {
        if (null != pd) {
            String spath = pd.getserializedFilepath();
            if (!TextUtils.isEmpty(spath)) {
                boolean breset = FileUtil.serializebookpartpage(spath, pd);
                if (!breset) {
                    TLog.log("NewReadBookActivity : updateseerializedbookpartpage : failed : " + spath);
                }
            }
        }
    }

    private Pagesdata getcurrentpagesdataobj(int iinnerpage, boolean bforcebemyself) {
        if (null != m_psds && null != m_psds[0]) {
            try {
                for (int i = 0; i < m_psds.length; i++) {
                    if (null != m_psds[i]) {
                        if (m_psds[i].pageisin(iinnerpage)) {
                            return m_psds[i];
                        }
                    }
                }
            } catch (Exception e) {
            }
            return bforcebemyself ? null : m_psds[0];
        }
        return null;
    }

    private void autodoreadtometypeotherpage() {
        if (DefaultSettings.BOOKREADTYPE_READTOME != m_ireadtype) {
            return;
        }
        if (m_inowpagepos < 0 && m_inowpagepos >= m_ibd_totalcount - 1) {
            return;
        }
        Pagesdata psd = getcurrentpagesdataobj(m_inowpagepos, true);
        if (null != psd) {
            Pagedata pd = psd.getpagedata(m_inowpagepos);
            if (null != pd) {
                if (DefaultSettings.ms_Json_BookPageType_page != pd.getpageType()) {
                    if (!TextUtils.isEmpty(pd.getTitleMp3())) {

                    } else {
                        m_hreadtomeslippage.sendEmptyMessageDelayed(0, 2500);
                    }
                } else {
                    if (DefaultSettings.BOOKREADTYPE_READTOME == m_ireadtype) {
                        KokRegion kr = pd.getKokRegion();
                        if (null == kr) {
                            m_hreadtomeslippage.sendEmptyMessageDelayed(0, 2500);
                        } else {
                            String smp3[] = kr.getallaudiofilepathes();
                            if (null == smp3 || smp3.length <= 0) {
                                m_hreadtomeslippage.sendEmptyMessageDelayed(0, 2500);
                            }
                        }
                    }
                }
            }
        }
    }

    private Handler m_hreadtomeslippage = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null == m_vpbookpage) {
                m_hreadtomeslippage.sendEmptyMessageDelayed(0, 2000);
            } else {
                
			    /*m_inowpagepos++;
	        	if(null != m_vpapagesadapter) {
	    			m_vpapagesadapter.recordselectedpage(m_inowpagepos + 1);
	        	}
	        	*/

                m_vpbookpage.setCurrentItem(m_inowpagepos + 1);
                //autodoreadtometypeotherpage();
            }
        }
    };

    private void autodoreadtometypebookpage(boolean toflip) {
        if (DefaultSettings.BOOKREADTYPE_READTOME == m_ireadtype && toflip) {
            if (m_inowpagepos >= 0 && m_inowpagepos < m_ibd_totalcount - 1) {
	        	/*m_inowpagepos++;
	        	if(null != m_vpapagesadapter) {
	    			m_vpapagesadapter.recordselectedpage(m_inowpagepos);
	        	}*/
                if (null != m_vpbookpage) {
/*	        		if(null == m_readtometransfwer) {
	        			m_readtometransfwer = new ViewPagerTransformer();
	        		}
	        		m_vpbookpage.setPageTransformer(true, m_readtometransfwer);	 */
                    m_vpbookpage.setCurrentItem(m_inowpagepos + 1);
                }
            }
        }
    }

    private int getscaledsizeXdirection(int idefaultsize) {
        return (int) (idefaultsize * m_dsi.m_fscreendensity * m_fratiox + 0.499f);
    }

    private int getscaledsizeYdirection(int idefaultsize) {
        return (int) (idefaultsize * m_dsi.m_fscreendensity * m_fratioy);
    }

    private class ViewPagerTransformer implements ViewPager.PageTransformer {
        private static final float MIN_SCALE = 0.85f;
        private static final float MIN_ALPHA = 0.5f;

        @Override
        public void transformPage(View view, float position) {
            int pageWidth = view.getWidth();
            int pageHeight = view.getHeight();
            //MyLog.dee("MyLog :  transformPage : pageWidth = "+ pageWidth + ", pageHeight = " + pageHeight + ", position = " + position);
            if (position < -1) { // [-Infinity,-1)
                // This page is way off-screen to the left.
                //view.setAlpha(0);         
            } else if (position <= 1) { // [-1,1]
                // Modify the default slide transition to shrink the page as well
                float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
                float vertMargin = pageHeight * (1 - scaleFactor) / 2;
                float horzMargin = pageWidth * (1 - scaleFactor) / 2;
                if (position < 0) {
                    view.setTranslationX(horzMargin - vertMargin / 2);
                } else {
                    view.setTranslationX(-horzMargin + vertMargin / 2);
                }
                // Scale the page down (between MIN_SCALE and 1)             
                //view.setScaleX(scaleFactor);            
                //view.setScaleY(scaleFactor);
                // Fade the page relative to its size.             
                //view.setAlpha(MIN_ALPHA +(scaleFactor - MIN_SCALE) / (1 - MIN_SCALE) * (1 - MIN_ALPHA)); 
            } else { // (1,+Infinity]
                // This page is way off-screen to the right.
                //view.setAlpha(0);        
            }
        }
    }

    private void floatbarhideprocess() {
        if (0 == m_ifloatbarshow.get()) {
            // the float bar had been hidden
            return;
        }
        m_hfloatbarhideprocess.sendEmptyMessageDelayed(0, 2500);
    }

    private Handler m_hfloatbarhideprocess = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (!m_vpapagesadapter.isquizview(m_inowpagepos)) {
                hidetopFloatbar();
            }
            hideBottomGallery();
        }
    };

    private void showtopFloatbar() {
        if (0 != m_ifloatbarshow.get()) {
            return;
        }
        m_ifloatbarshow.set(1);
       //AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
        TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, -1.0f,
                Animation.RELATIVE_TO_SELF, 0.0f);
        anim.setRepeatCount(0);
        anim.setDuration(250);
        anim.setAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                m_rlbooktopfloatbar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                m_ifloatbarshow.incrementAndGet();
                //m_hfloatbarhideprocess.sendEmptyMessageDelayed(0, 2500);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        m_rlbooktopfloatbar.startAnimation(anim);
    }

    private void hidetopFloatbar() {
        if (null == m_vpapagesadapter) {
            return;
        }
        if (2 != m_ifloatbarshow.get()) {
            return;
        }
        m_ifloatbarshow.set(-1);
        //AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
        TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, -1.0f);
        anim.setRepeatCount(0);
        anim.setDuration(250);
        anim.setAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (-1 == m_ifloatbarshow.get()) {
                    m_rlbooktopfloatbar.setVisibility(View.GONE);
                }
                m_ifloatbarshow.incrementAndGet();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        m_rlbooktopfloatbar.startAnimation(anim);
    }

    private Handler m_hshowworddict = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (MSG_HIDEDICTVIEW == msg.what) {
                if (m_bworddictisshow.get() > 0) {
                    backpressclosedictionary(true);
                }
            }
        }
    };

    private void backpressclosedictionary(/*boolean bcloseimmediately, */boolean withanim) {
        if (withanim) {
            hideWordDictView();
        } else {
            hideWordDictViewWithoutAnim();
        }

    }

    private void clearworddictdescviewid() {
        if (null != m_vwdworddictcontainer) {
            int iviewid = -1;
            try {
                synchronized (this) {
                    iviewid = ((Integer) m_vwdworddictcontainer.getTag()).intValue();
                }
                if (iviewid >= 0) {
                    freeexclusivetagId(iviewid);
                }
            } catch (Exception e) {
            }
            m_vwdworddictcontainer.setTag(NewViewWordDictdesc.INVALIDVIEWID);
        }
    }

    private void liquidateWorddictView() {
        if (null != m_vwdworddictcontainer) {
            m_vwdworddictcontainer.stopgetworddictionarydata();
            m_vwdworddictcontainer.clearviews();
        }
    }

    private void showhorizontalbookwaitingpage(boolean bshow) {
        if (null == m_ivhorizonwait) {
            m_ivhorizonwait = (ImageView) findViewById(R.id.iv_horizonwait);
        }
        m_ivhorizonwait.setVisibility(bshow ? View.VISIBLE : View.GONE);
        if (null != m_rlrealreadbook) {
            m_rlrealreadbook.setVisibility(bshow ? View.INVISIBLE : View.VISIBLE);
        }
    }

    // added by wang qian below
    public final static int BOOKTOPMENUBAR_HEIGHT = DefaultSettings.BANNERTITLE_HEIGHT_V;//42;

    public final static int Get_WORDDICTDESC_WORKREGION_MAXWIDTH(boolean bislandscape, float fscreendensity) {
        if (fscreendensity - 2.9f > 0.05f) {
            return bislandscape ? WORDDICTDESC_WORKREGION_MAXWIDTH_LANDSCAPEBOOK_3 : WORDDICTDESC_WORKREGION_MAXWIDTH_VERTICALBOOK_3;
        }
        if (fscreendensity - 1.9f > 0.05f) {
            return bislandscape ? WORDDICTDESC_WORKREGION_MAXWIDTH_LANDSCAPEBOOK_2 : WORDDICTDESC_WORKREGION_MAXWIDTH_VERTICALBOOK_2;
        }
        return bislandscape ? WORDDICTDESC_WORKREGION_MAXWIDTH_LANDSCAPEBOOK : WORDDICTDESC_WORKREGION_MAXWIDTH_VERTICALBOOK;
    }

    private final static int WORDDICTDESC_WORKREGION_MAXWIDTH_VERTICALBOOK = 480;
    private final static int WORDDICTDESC_WORKREGION_MAXHEIGHT_VERTICALBOOK = 720;
    private final static int WORDDICTDESC_WORKREGION_MAXWIDTH_LANDSCAPEBOOK = 480;
    private final static int WORDDICTDESC_WORKREGION_MAXHEIGHT_LANDSCAPEBOOK = 620;
    private final static int WORDDICTDESC_WORKREGION_MAXWIDTH_VERTICALBOOK_2 = 640;
    private final static int WORDDICTDESC_WORKREGION_MAXHEIGHT_VERTICALBOOK_2 = 800;
    private final static int WORDDICTDESC_WORKREGION_MAXWIDTH_LANDSCAPEBOOK_2 = 720;
    private final static int WORDDICTDESC_WORKREGION_MAXHEIGHT_LANDSCAPEBOOK_2 = 640;
    private final static int WORDDICTDESC_WORKREGION_MAXWIDTH_VERTICALBOOK_3 = 800;
    private final static int WORDDICTDESC_WORKREGION_MAXHEIGHT_VERTICALBOOK_3 = 1280;
    private final static int WORDDICTDESC_WORKREGION_MAXWIDTH_LANDSCAPEBOOK_3 = 1280;
    private final static int WORDDICTDESC_WORKREGION_MAXHEIGHT_LANDSCAPEBOOK_3 = 880;
    public final static int BOOKTOPMENUBAR_BOOKSETTINGSMARGIN = 8;

    @Override
    public void setViewPagerCanTurning(boolean enable) {
        // TODO Auto-generated method stub
        if (m_vpbookpage != null) {
            CustomViewPager customvp = (CustomViewPager) m_vpbookpage;
            customvp.setscrollable(enable);
        }
    }


    private ArrayList<BottomGalleryDataObj> getBottomGalleryData() {
        if (m_ibd_totalcount <= 0) return null;
        if (m_pdcurrent == null) return null;
        ArrayList<BottomGalleryDataObj> retlist = null;
        for (int i = 0; i < m_ibd_totalcount; i++) {
            Bookpagesummary bps = m_pdcurrent.getBookPageSummary(i);
            if (bps != null) {
                BottomGalleryDataObj obj = new BottomGalleryDataObj();
                obj.mName = bps.m_name;
                obj.mPageNumber = bps.m_ipagenumber;
                obj.mThumb = bps.m_thumb;
                obj.mType = bps.m_itype;
                obj.mIndex = bps.m_index;

                if (retlist == null) {
                    retlist = new ArrayList<BottomGalleryDataObj>();
                }
                retlist.add(obj);
            }
        }
        if (retlist != null && retlist.size() > 0) {
            if (m_bbd_hasquiz) {
                BottomGalleryDataObj lastobj = retlist.get(retlist.size() - 1);
                if (lastobj != null && lastobj.mType == DefaultSettings.ms_Json_BookPageType_backover) {
                    retlist.remove(lastobj);
                }

                BottomGalleryDataObj obj = new BottomGalleryDataObj();
                obj.mName = null;
                obj.mPageNumber = -1;
                obj.mThumb = null;
                obj.mIndex = 1;
                obj.mType = DefaultSettings.ms_Json_BookPageType_bookquiz;
                retlist.add(obj);
            }
        }
        return retlist;
    }

    private boolean mBottomGalleryClicked = false;
    private long m_lastGalleryClickedTime = 0;

    private void initBottomGallery() {
        mBottomGalleryLayout = (RelativeLayout) findViewById(R.id.bottomgallerylayout);
        mBottomGallery = (BottomGallery) findViewById(R.id.bottomgallery);
        mBottomGallery.setSaveEnabled(false);

        mGalleryDataList = getBottomGalleryData();
        if (mGalleryDataList != null && mGalleryDataList.size() > 0) {
            mGalleryAdapter = new BottomGalleryAdapter(this, mGalleryDataList);
            mBottomGallery.setAdapter(mGalleryAdapter);
            int selected = Integer.MAX_VALUE / 2;
            int offset = selected % (mGalleryDataList.size()) - m_inowpagepos;
            mBottomGallery.setSelection(selected - offset);
            mGalleryAdapter.setSelection(selected - offset);
            mBottomGallery.setSpacing((int) getResources().getDimension(R.dimen.thumbnail_inveval));
            mBottomGallery.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View view,
                                        int position, long arg3) {
                    // TODO Auto-generated method stub
                    int toselect = position % mGalleryDataList.size();
                    //MyLog.d("logautokok onItemClick " + position + " m_bautokok = " + m_bautokok);
                    mGalleryAdapter.setSelection(position);
                    mBottomGalleryClicked = true;
                    m_vpbookpage.setCurrentItem(toselect);



                    long time = System.currentTimeMillis();
                    long timeD = time - m_lastGalleryClickedTime;
                    if (timeD > 500) {
                        UmsAgent.onEvent(ReadBookActivity.this, "Page_clk_catalog");
                        m_lastGalleryClickedTime = time;
                        TLog.log("Page_clk_catalog " + time);
                    }

                }
            });
        }
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mBottomGalleryLayout.getLayoutParams();
        //lp.height = 400;
        lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        mBottomGalleryLayout.setLayoutParams(lp);
    }

    private void showBottomGallery() {
        if (mGalleryAdapter == null) return;
        if (0 != m_bottomGalleryShow.get()) {
            return;
        }
        m_bottomGalleryShow.set(1);
        //AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
        TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                                                         Animation.RELATIVE_TO_SELF, 0.0f,
                                                         Animation.RELATIVE_TO_SELF, 1.0f,
                                                         Animation.RELATIVE_TO_SELF, 0.0f);
        anim.setRepeatCount(0);
        anim.setDuration(250);
        anim.setAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                mBottomGalleryLayout.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                m_bottomGalleryShow.incrementAndGet();
                //m_hfloatbarhideprocess.sendEmptyMessageDelayed(0, 2500);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        mBottomGalleryLayout.startAnimation(anim);
    }

    private void hideBottomGallery() {
        if (mGalleryAdapter == null) return;
        if (null == m_vpapagesadapter) {
            return;
        }
        if (2 != m_bottomGalleryShow.get()) {
            return;
        }
        m_bottomGalleryShow.set(-1);
       // AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
        TranslateAnimation anim = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 1.0f);
        anim.setRepeatCount(0);
        anim.setDuration(250);
        anim.setAnimationListener(new AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (-1 == m_bottomGalleryShow.get()) {
                    mBottomGalleryLayout.setVisibility(View.GONE);
                }
                m_bottomGalleryShow.incrementAndGet();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
        mBottomGalleryLayout.startAnimation(anim);
    }

    private void initBookMark() {
        mBookMarkLayout = (RelativeLayout) findViewById(R.id.bookmarklayout);
        mReadToMeBtn = (ImageButton) findViewById(R.id.readtome);
        mReadByMySelfBtn = (ImageButton) findViewById(R.id.readbymyself);
        mHandView = (ImageView) findViewById(R.id.hand);

        mReadToMeBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                m_ireadtype = DefaultSettings.BOOKREADTYPE_READTOME;
                m_bautokok = true;
                UmsAgent.onEvent(ReadBookActivity.this, "Guide_clk_readme");
                hideBookMark();
                //autodoreadtometypeotherpage();
                autokokforcurrentpage(m_inowpagepos);

            }
        });

        mReadByMySelfBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                UmsAgent.onEvent(ReadBookActivity.this, "Guide_clk_readmyself");
                m_ireadtype = DefaultSettings.BOOKREADTYPE_READMYSELF;
                getautokokstatus();
                mHandView.startAnimation(mHandAnim);
            }
        });

        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mBookMarkLayout.getLayoutParams();
        lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        lp.rightMargin = (int) getResources().getDimension(R.dimen.bookmark_margin);
        lp.topMargin = -(int) getResources().getDimension(R.dimen.bookmark_topmargin);
        ;
        mBookMarkLayout.setLayoutParams(lp);

        mBookmarkOut = AnimationUtils.loadAnimation(this, R.anim.bookmark_left_out);
        mBookmarkOut.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationEnd(Animation arg0) {
                // TODO Auto-generated method stub
                mBookMarkLayout.setVisibility(View.GONE);
                m_bookmarkShow.incrementAndGet();
            }

            @Override
            public void onAnimationRepeat(Animation arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationStart(Animation arg0) {
                // TODO Auto-generated method stub
                mReadToMeBtn.setEnabled(false);
                mReadByMySelfBtn.setEnabled(false);
            }
        });

        mBookmarkIn = AnimationUtils.loadAnimation(this, R.anim.bookmark_right_in);
        ;
        mBookmarkIn.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationEnd(Animation arg0) {
                // TODO Auto-generated method stub
                mReadToMeBtn.setEnabled(true);
                mReadByMySelfBtn.setEnabled(true);
                m_bookmarkShow.incrementAndGet();
            }

            @Override
            public void onAnimationRepeat(Animation arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationStart(Animation arg0) {
                // TODO Auto-generated method stub
                mReadToMeBtn.setEnabled(false);
                mReadByMySelfBtn.setEnabled(false);
                mBookMarkLayout.setVisibility(View.VISIBLE);

            }

        });


        if (m_inowpagepos == 0) {
            showBookMark();
        }

        mHandAnim = AnimationUtils.loadAnimation(this, R.anim.reader_hand_anim);
        mHandAnim.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationEnd(Animation arg0) {
                // TODO Auto-generated method stub
                mHandView.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onAnimationStart(Animation arg0) {
                // TODO Auto-generated method stub
                mHandView.setVisibility(View.VISIBLE);
            }
        });


    }

    private void showBookMark() {
        if (m_bookmarkShow.get() > 0) {
            return;
        }
        m_bookmarkShow.set(1);
        mBookMarkLayout.startAnimation(mBookmarkIn);
    }

    private void hideBookMark() {
        if (m_bookmarkShow.get() <= 0) {
            return;
        }
        m_bookmarkShow.set(-1);
        mBookMarkLayout.startAnimation(mBookmarkOut);
    }
    //added by wang qian above

    private Handler mSettingHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) m_llsettingsregion.getLayoutParams();
                lp.leftMargin = msg.arg1;
                lp.topMargin = msg.arg2;
                m_llsettingsregion.setLayoutParams(lp);
            } else if (msg.what == 1) {
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) m_llsettingsregion.getLayoutParams();
                lp.topMargin = msg.arg1;
                m_llsettingsregion.setLayoutParams(lp);
                //m_llsettingsregion.setVisibility(View.VISIBLE);
            }

        }
    };


    @Override
    public void onSettingBtnClicked() {
        // TODO Auto-generated method stub
        AlphaAnimation anim = null;
        int btn_height = (int) getResources().getDimension(R.dimen.booksetting_btn_width) +
                (int) getResources().getDimension(R.dimen.booksetting_btn_inteval);
        boolean hasKok = false;
        boolean hasPinyin = false;
        boolean hasAnotherLan = false;
        boolean hasTrans = false;

        Pagedata data = m_pdcurrent.getpagedata(m_inowpagepos);
        if (data != null) {
            hasKok = data.hasKok();
            hasPinyin = data.hasPinyin();
            if (!data.getEnglishPage()) {
                hasAnotherLan = data.hasEn();
            } else {
                hasAnotherLan = data.hasCn();
            }
            hasTrans = TextUtils.isEmpty(data.getTrans()) ? false : true;
        }
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) m_llsettingsregion.getLayoutParams();
        int temp_new_top_margin = lp.topMargin + (btn_height * ((hasKok ? 1 : 0) + (hasPinyin ? 1 : 0) + (hasAnotherLan ? 1 : 0) + (hasTrans?1:0)));
        if (m_bnshowspeed.getVisibility() == View.VISIBLE) {
            temp_new_top_margin += ((int)getResources().getDimension(R.dimen.booksetting_speed_btn_height) + (int) getResources().getDimension(R.dimen.booksetting_btn_inteval));
        }
        final int new_top_margin = temp_new_top_margin;

        if (2 == m_isettingsshow.get()) {
            m_isettingsshow.set(-1);
            anim = new AlphaAnimation(1.0f, 0.0f);
            m_bnbooksettings.setSelected(false);
            UmsAgent.onEvent(ReadBookActivity.this, "Toolbar_fold");
        } else if (0 == m_isettingsshow.get()) {
            m_isettingsshow.set(1);
            anim = new AlphaAnimation(0.0f, 1.0f);
            m_bnbooksettings.setSelected(true);

            UmsAgent.onEvent(ReadBookActivity.this, "Toolbar_unfold");

            int topMargin = (lp.topMargin - (btn_height * ((hasKok ? 1 : 0) + (hasPinyin ? 1 : 0) + (hasAnotherLan ? 1 : 0) + (hasTrans?1:0))));
            if (m_bnshowspeed.getVisibility() == View.VISIBLE) {
                topMargin -= ((int)getResources().getDimension(R.dimen.booksetting_speed_btn_height) + (int) getResources().getDimension(R.dimen.booksetting_btn_inteval));
            }
            int top_height = (int) getResources().getDimension(R.dimen.topbar_height)
                    + (int) getResources().getDimension(R.dimen.booksetting_btn_margin);

            if (topMargin < top_height) topMargin = top_height;
            lp.topMargin = topMargin;
            m_llsettingsregion.setLayoutParams(lp);
            m_llsettingsitems.setVisibility(View.INVISIBLE);

        }

        if (null != anim) {
            anim.setRepeatCount(0);
            anim.setDuration(1000);
            anim.setAnimationListener(new AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    if (1 == m_isettingsshow.get()) {
                        m_llsettingsitems.setVisibility(View.VISIBLE);
                    }
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    if (-1 == m_isettingsshow.get()) {
                        m_llsettingsitems.setVisibility(View.GONE);
                        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) m_llsettingsregion.getLayoutParams();
                        lp.topMargin = new_top_margin;
                        m_llsettingsregion.setLayoutParams(lp);
                    }
                    m_isettingsshow.incrementAndGet();
                    //m_bnbooksettings.modifyPosition();
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });
            m_llsettingsitems.startAnimation(anim);
        }
    }

    private void initTransLayout() {
        mTransLayout = (TouchMoveLinearLayout) findViewById(R.id.translayout);
        mTransLayout.setScreenSize(mScreenWidth,mScreenHeight);
        mTranView = (TextView) findViewById(R.id.transview);
        mTranView.setMovementMethod(ScrollingMovementMethod.getInstance());


        //resetTraansLayoutPosition();

/*        if (m_inowpagepos > 0) {
            pagedata data = m_pdcurrent.getpagedata(m_inowpagepos);
            if (data != null) {
                mTranView.setText(data.getTrans());
            }
        }*/
        mTransLayout.setVisibility(View.INVISIBLE);
    }



    private void showTransLayout(String trans) {
        if (m_transShow.get() > 0) {
            return;
        }
        resetTraansLayoutPosition();
        m_transShow.set(1);
        mTranView.setText(trans);
        int[] local = new int[2];
        m_bnshowtrans.getLocationOnScreen(local);
        int btn_width = (int)getResources().getDimension(R.dimen.booksetting_btn_width);
        int btn_height = (int)getResources().getDimension(R.dimen.booksetting_btn_width);
        local[0] += (btn_width / 2);
        local[1] += (btn_height / 2);
        int[] translayoutlocal = new int[2];
        //mTransLayout.getLocationOnScreen(translayoutlocal);
        RelativeLayout.LayoutParams rp = (RelativeLayout.LayoutParams) mTransLayout.getLayoutParams();
        if (rp != null) {
            translayoutlocal[0] = rp.leftMargin;
            translayoutlocal[1] = rp.topMargin;
        }
        float x_offset = local[0] - translayoutlocal[0];
        float y_offset = local[1] - translayoutlocal[1];

        mTransShowScaleAnimation = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f,
                Animation.ABSOLUTE, x_offset, Animation.ABSOLUTE, y_offset);
        mTransShowScaleAnimation.setDuration(500);
        mTransShowScaleAnimation.setAnimationListener(new AnimationListener() {
              @Override
              public void onAnimationStart(Animation animation) {
                  mTransLayout.setVisibility(View.VISIBLE);
              }

              @Override
              public void onAnimationEnd(Animation animation) {
                  if (m_transShow.get() != 0) {
                      m_transShow.incrementAndGet();
                      mTransShowScaleAnimation = null;
                  }
              }

              @Override
              public void onAnimationRepeat(Animation animation) {
              }
          }
        );
        mTransLayout.setAnimation(mTransShowScaleAnimation);
        mTransShowScaleAnimation.startNow();
    }

    private void resetTraansLayoutPosition() {

        int width = mTransLayout.getWidth();
        int height = mTransLayout.getHeight();

        RelativeLayout.LayoutParams rp = (RelativeLayout.LayoutParams) mTransLayout.getLayoutParams();
        if (rp != null) {
            rp.leftMargin = (mScreenWidth - width) / 2;
            rp.topMargin = (mScreenHeight - height) / 2;
            mTransLayout.setLayoutParams(rp);
        }
    }

    private void hideTransLayout() {
        if (m_transShow.get() <= 0) {
            return;
        }
        m_transShow.set(-1);

        int[] local = new int[2];
        if (m_bnshowtrans.getVisibility() == View.VISIBLE) {
            m_bnshowtrans.getLocationOnScreen(local);
        } else if (m_bnbooksettings.getVisibility() == View.VISIBLE) {
            m_bnbooksettings.getLocationOnScreen(local);
        } else {
            hideTransLayoutWithoutAnimation();
            return;
        }
        int btn_width = (int)getResources().getDimension(R.dimen.booksetting_btn_width);
        int btn_height = (int)getResources().getDimension(R.dimen.booksetting_btn_width);
        local[0] += (btn_width / 2);
        local[1] += (btn_height / 2);

        int[] translayoutlocal = new int[2];
        mTransLayout.getLocationOnScreen(translayoutlocal);
        float x_offset = local[0] - translayoutlocal[0];
        float y_offset = local[1] - translayoutlocal[1];


        mTransHideScaleAnimation = new ScaleAnimation(1.0f, 0.0f, 1.0f, 0.0f,
                Animation.ABSOLUTE, x_offset, Animation.ABSOLUTE, y_offset);
        mTransHideScaleAnimation.setDuration(500);
        mTransHideScaleAnimation.setAnimationListener(new AnimationListener() {
              @Override
              public void onAnimationStart(Animation animation) {
              }

              @Override
              public void onAnimationEnd(Animation animation) {
                  if (m_transShow.get() == -1) {
                      m_transShow.incrementAndGet();
                      //resetTraansLayoutPosition();
                      mTransLayout.setVisibility(View.INVISIBLE);
                      mTransHideScaleAnimation = null;

                  }
                  mTransHideScaleAnimation = null;
              }

              @Override
              public void onAnimationRepeat(Animation animation) {
              }
          }
        );
        mTransLayout.setAnimation(mTransHideScaleAnimation);
        mTransHideScaleAnimation.startNow();

    }

    private void hideTransLayoutWithoutAnimation() {
        if (m_bnshowtrans == null) {
            return;
        }
        m_ishowthrans = 0;
        m_bnshowtrans.setSelected(m_ishowthrans > 0);
        if (m_transShow.get() == 0) {
            return;
        }

        m_transShow.set(0);
        //resetTraansLayoutPosition();
        mTransLayout.setVisibility(View.INVISIBLE);
    }

    private Handler mSpeedConvertHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String path = (String)msg.obj;
            setSupportSpeecConvert(msg.arg1, path, msg.arg2);
        }
    };

    @Override
    public void addSpeedConvertTask(int pageindex, String filepath, int index, int totoal_num, int speed, int bookid ) {
        if (mSpeedConvertThread == null) {


            mSpeedConvertThread = new SpeedRegulationThread(this, mSpeedConvertHandler);
            mSpeedConvertThread.start();
        }

        SpeedConvertItem item = new SpeedConvertItem();
        item.mPageIndex = pageindex;
        item.mSpeed = speed;
        item.mIndex = index;
        item.mTotalFileNumber = totoal_num;
        item.mSoundFilePath = filepath;
        item.mBookId = bookid;

        mSpeedConvertThread.addSpeedConvertItem(item);
    }

    @Override
    public void setSupportSpeecConvert(int pageindex, String path, int bookid) {
        TLog.log("Convert finish " + path + " page = " + pageindex);
        if (bookid == m_ibookid) {
            TLog.log("Convert set " + path + " page = " + pageindex);
            synchronized (mSpeedConvertState) {
                mSpeedConvertState[pageindex] = true;
            }
        }
    }

    @Override
    public void getToCover() {



        int selected = mGalleryAdapter.getSelection();

        int offset = mGalleryDataList.size() - selected % mGalleryDataList.size();

        mBottomGallery.setSelection(selected - offset);
        mGalleryAdapter.setSelection(selected - offset);

        m_vpbookpage.setCurrentItem(0);
    }

    @Override
    public void hideTopBottomBarForScale() {
        if (m_ifloatbarshow.get() > 0) {
            hidetopFloatbar();
        }

        if (m_bottomGalleryShow.get() > 0) {
            hideBottomGallery();
        }
    }

    @Override
    public void hideTransOrDict() {
        if (m_transShow.get() > 0) {
            m_ishowthrans = 0;
            m_bnshowtrans.setSelected(m_ishowthrans > 0);
            hideTransLayout();
        }
        if (m_bworddictisshow.get() > 0) {
            backpressclosedictionary(true);
        }
    }



    private void  addRecord(){
       // recordDao =new ReadRecordEntityDao();
        ReadRecord record =new ReadRecord();
            record.setUserId((int)userId);
            record.setBookId(m_ibooknetid);
            record.setEnterTime(System.currentTimeMillis());
            record.setOutTime(0L);
       // recordDao.insertEntity(record);
    }

    int     mCurrentHotRegionPageIndex = -1;
    int     mCurrentHotRegionIndex = - 1;


    @Override
    public void hotRegionBtnClicked(int innerpage, int hotregioninde) {
        if (mDuringScroll) {
            return;
        }
        boolean bautokok;

        if (mCurrentHotRegionPageIndex >= 0 && innerpage >= 0 && mCurrentHotRegionPageIndex == innerpage
           && mCurrentHotRegionIndex >= 0  && hotregioninde >= 0 && mCurrentHotRegionIndex == hotregioninde) {
            bautokok = false;
            mCurrentHotRegionPageIndex = -1;
            mCurrentHotRegionIndex = -1;
        } else {
            bautokok = true;
            mCurrentHotRegionPageIndex = -1;
            mCurrentHotRegionIndex = -1;
        }

        int icur = m_vpbookpage.getCurrentItem();
        if (icur >= 0) {
            NewBookPageView bpv = m_vpapagesadapter.getbookpageview(icur);
            if (null != bpv) {
                if (bautokok) {
                    if (bpv.starthotkok(hotregioninde)) {
                        mCurrentHotRegionPageIndex = innerpage;
                        mCurrentHotRegionIndex = hotregioninde;
                        if (m_bautokok) {
                            setautokokstatus(ms_iautokokwait);

                            boolean support_speed = false;
                            synchronized (mSpeedConvertState) {
                                support_speed = mSpeedConvertState[icur];
                            }
                            if (support_speed) {

                                changeSettingBarForSpeedBtn(false);
                                mSpeedBtnShow = false;
                                m_bnshowspeed.setVisibility(View.GONE);
                            }
                        }
                    }
                } else {
                    bpv.requestClosePlaykokProcess();
                }
            }
        }
    }

    private void getpinyinstatus() {
        m_ishowpinyin = 1;
    }


}
